在Python中,可以拆分一个字符串并将其分配给变量:
ip,port = '127.0.0.1:5432'.split(':')
但在戈兰,似乎不工作:
ip,port := strings.Split("127.0.0.1:5432",":") // assignment count mismatch: 2 = 1
问题:如何拆分一个字符串并在一个步骤中赋值?
两个步骤,例如,
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) }
输出:
127.0.0.1 5432
一步,例如,
package main import ( "fmt" "net" ) func main() { host,port,err := net.SplitHostPort("127.0.0.1:5432") fmt.Println(host,err) }
输出:
127.0.0.1 5432 <nil>