go - How to split a string and assign it to variables in Golang? -
in python possible split string , assign variables:
ip, port = '127.0.0.1:5432'.split(':')
but in golang not seem work:
ip, port := strings.split("127.0.0.1:5432", ":") // assignment count mismatch: 2 = 1
question: how split string , assign values in 1 step?
two steps, example,
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) }
output:
127.0.0.1 5432
one step, example,
package main import ( "fmt" "net" ) func main() { host, port, err := net.splithostport("127.0.0.1:5432") fmt.println(host, port, err) }
output:
127.0.0.1 5432 <nil>
Comments
Post a Comment