在 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>
关于string - 如何拆分字符串并将其分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16551354/