How to split a string and assign it to variables

前端 未结 9 1578
无人及你
无人及你 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:28

    Two steps, for example,

    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)
    }
    

    Output:

    127.0.0.1 5432
    

    One step, for example,

    package main
    
    import (
        "fmt"
        "net"
    )
    
    func main() {
        host, port, err := net.SplitHostPort("127.0.0.1:5432")
        fmt.Println(host, port, err)
    }
    

    Output:

    127.0.0.1 5432 
    

提交回复
热议问题