Home >Backend Development >Golang >How to Split Strings and Assign Values in Go?
In Python, splitting a string and assigning the resulting values to variables can be done in one step using the split() method and multiple assignment. However, in Go, this approach fails with the error "assignment count mismatch."
To split a string and assign values in Go, there are two possible approaches:
Two-Step Approach:
package main import ( "fmt" "strings" ) func main() { s := strings.Split("127.0.0.1:5432", ":") ip, port := s[0], s[1] fmt.Println(ip, port) }
One-Step Approach Using net.SplitHostPort():
This approach leverages the net.SplitHostPort() function, which is designed for extracting the host and port from a network address:
package main import ( "fmt" "net" ) func main() { host, port, err := net.SplitHostPort("127.0.0.1:5432") fmt.Println(host, port, err) }
The above is the detailed content of How to Split Strings and Assign Values in Go?. For more information, please follow other related articles on the PHP Chinese website!