How to split a string and assign it to variables

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

    Golang does not support implicit unpacking of an slice (unlike python) and that is the reason this would not work. Like the examples given above, we would need to workaround it.

    One side note:

    The implicit unpacking happens for variadic functions in go:

    func varParamFunc(params ...int) {
    
    }
    
    varParamFunc(slice1...)
    
    0 讨论(0)
  • 2020-12-07 11:27

    What you are doing is, you are accepting split response in two different variables, and strings.Split() is returning only one response and that is an array of string. you need to store it to single variable and then you can extract the part of string by fetching the index value of an array.

    example :

     var hostAndPort string
        hostAndPort = "127.0.0.1:8080"
        sArray := strings.Split(hostAndPort, ":")
        fmt.Println("host : " + sArray[0])
        fmt.Println("port : " + sArray[1])
    
    0 讨论(0)
  • 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 <nil>
    
    0 讨论(0)
提交回复
热议问题