Home >Backend Development >Golang >How to Split Strings and Assign Variables in Go?
Splitting Strings and Assigning Variables in Go
Unlike Python, which allows for simultaneous string splitting and variable assignment, Go requires a slightly different approach.
Two-Step Split
One method is to split the string into a slice and then assign the values:
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 Split
Go's net package provides a convenient SplitHostPort function for splitting a host-port string directly into variables:
package main import ( "fmt" "net" ) func main() { host, port, err := net.SplitHostPort("127.0.0.1:5432") fmt.Println(host, port, err) }
Both approaches effectively allow you to split a string and assign the resulting values to variables in Go.
The above is the detailed content of How to Split Strings and Assign Variables in Go?. For more information, please follow other related articles on the PHP Chinese website!