Unpack slices on assignment?

后端 未结 3 644
误落风尘
误落风尘 2020-12-25 09:36

Is there an elegant way in Go to do multiple assignments from arrays like in Python? Here is a Python example of what I\'m trying to do (split a string and then assign the r

3条回答
  •  臣服心动
    2020-12-25 10:14

    If your function is meant to split a string only by the first occurrence of the separator, you can always make your own function:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func Split(s, sep string) (string, string) {
        // Empty string should just return empty
        if len(s) == 0 {
            return s, s
        }   
    
        slice := strings.SplitN(s, sep, 2)
    
        // Incase no separator was present
        if len(slice) == 1 {
            return slice[0], ""
        }
    
        return slice[0], slice[1]
    }
    
    func main() {
        a, b := Split("foo;bar;foo", ";")
        fmt.Println(a, b)
    }
    

    Output:

    foo bar;foo

    Playground

提交回复
热议问题