How to split a string and assign it to variables

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

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        strs := strings.Split("127.0.0.1:5432", ":")
        ip := strs[0]
        port := strs[1]
        fmt.Println(ip, port)
    }
    

    Here is the definition for strings.Split

    // Split slices s into all substrings separated by sep and returns a slice of
    // the substrings between those separators.
    //
    // If s does not contain sep and sep is not empty, Split returns a
    // slice of length 1 whose only element is s.
    //
    // If sep is empty, Split splits after each UTF-8 sequence. If both s
    // and sep are empty, Split returns an empty slice.
    //
    // It is equivalent to SplitN with a count of -1.
    func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }
    

提交回复
热议问题