How to split a string and assign it to variables

前端 未结 9 1590
无人及你
无人及你 2020-12-07 10:27

In Python it is possible to split a string and assign it to variables:

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

but in Go it does not see

9条回答
  •  没有蜡笔的小新
    2020-12-07 11:11

    The IPv6 addresses for fields like RemoteAddr from http.Request are formatted as "[::1]:53343"

    So net.SplitHostPort works great:

    package main
    
        import (
            "fmt"
            "net"
        )
    
        func main() {
            host1, port, err := net.SplitHostPort("127.0.0.1:5432")
            fmt.Println(host1, port, err)
    
            host2, port, err := net.SplitHostPort("[::1]:2345")
            fmt.Println(host2, port, err)
    
            host3, port, err := net.SplitHostPort("localhost:1234")
            fmt.Println(host3, port, err)
        }
    

    Output is:

    127.0.0.1 5432 
    ::1 2345 
    localhost 1234 
    

提交回复
热议问题