How to split a string and assign it to variables

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

    Since go is flexible an you can create your own python style split ...

    package main
    
    import (
        "fmt"
        "strings"
        "errors"
    )
    
    type PyString string
    
    func main() {
        var py PyString
        py = "127.0.0.1:5432"
        ip, port , err := py.Split(":")       // Python Style
        fmt.Println(ip, port, err)
    }
    
    func (py PyString) Split(str string) ( string, string , error ) {
        s := strings.Split(string(py), str)
        if len(s) < 2 {
            return "" , "", errors.New("Minimum match not found")
        }
        return s[0] , s[1] , nil
    }
    

提交回复
热议问题