如何分割一个string并将其分配给Golang中的variables?

在Python中,可以分割一个string并将其分配给variables:

ip, port = '127.0.0.1:5432'.split(':') 

但是在Golang中,它似乎不起作用:

 ip, port := strings.Split("127.0.0.1:5432", ":") // assignment count mismatch: 2 = 1 

问题:如何分割一个string并在一个步骤中分配值?

例如,两个步骤,

 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> 

由于go灵活,你可以创build自己的python风格拆分…

 package main import ( "fmt" "strings" "errors" ) type PyString string func main() { var py PyString py = "127.0.0.1:5432" ip, port , err := py.Split(":") // Python Style fmt.Println(ip, port, err) } func (py PyString) Split(str string) ( string, string , error ) { s := strings.Split(string(py), str) if len(s) < 2 { return "" , "", errors.New("Minimum match not found") } return s[0] , s[1] , nil }