Friday, April 22, 2016

How to split a string and assign it to variables in golang?

How to split a string and assign it to variables in golang?

Solution 1:

    s := strings.Split("127.0.0.1:5432", ":")
    ip, port := s[0], s[1]
    fmt.Println(ip, port)

Solution 2:

    host, port, err := net.SplitHostPort("127.0.0.1:5432")
    fmt.Println(host, port, err)

Solution 3:

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
}

Reference:

http://stackoverflow.com/questions/16551354/how-to-split-a-string-and-assign-it-to-variables-in-golang

No comments: