在Python中,可以分割字符串并将其分配给变量:
ip, port = '127.0.0.1:5432'.split(':')
但在Go中似乎无效:
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, port, err) }
127.0.0.1 5432 <nil>