How to split a string and assign it to variables

StringGoSplit

String Problem Overview


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 seem to work:

ip, port := strings.Split("127.0.0.1:5432", ":")
// assignment count mismatch: 2 = 1

Question: How to split a string and assign values in one step?

String Solutions


Solution 1 - String

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>

Solution 2 - String

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
}

Solution 3 - String

The IPv6 addresses for fields like RemoteAddr from http.Request are formatted as "[::1]:53343"

So net.SplitHostPort works great:

package main

    import (
        "fmt"
        "net"
    )

    func main() {
		host1, port, err := net.SplitHostPort("127.0.0.1:5432")
		fmt.Println(host1, port, err)

		host2, port, err := net.SplitHostPort("[::1]:2345")
		fmt.Println(host2, port, err)

		host3, port, err := net.SplitHostPort("localhost:1234")
		fmt.Println(host3, port, err)
    }

Output is:

127.0.0.1 5432 <nil>
::1 2345 <nil>
localhost 1234 <nil>

Solution 4 - String

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) }

Solution 5 - String

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...)

Solution 6 - String

There's are multiple ways to split a string :

  1. If you want to make it temporary then split like this:

_

import net package

host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)

2. Split based on struct :

  • Create a struct and split like this

_

type ServerDetail struct {
    Host       string
    Port       string
    err        error
}

ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port

Now use in you code like ServerDetail.Host and ServerDetail.Port

If you don't want to split specific string do it like this:

type ServerDetail struct {
    Host       string
    Port       string
}

ServerDetail = strings.Split([Your_String], ":") // Common split method

and use like ServerDetail.Host and ServerDetail.Port.

That's All.

Solution 7 - String

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])

Solution 8 - String

As a side note, you can include the separators while splitting the string in Go. To do so, use strings.SplitAfter as in the example below.

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("%q\n", strings.SplitAfter("z,o,r,r,o", ","))
}

Solution 9 - String

**In this function you can able to split the function by golang using array of strings**

func SplitCmdArguments(args []string) map[string]string {
	m := make(map[string]string)
	for _, v := range args {
		strs := strings.Split(v, "=")
		if len(strs) == 2 {
			m[strs[0]] = strs[1]
		} else {
			log.Println("not proper arguments", strs)
		}
	}
	return m
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPytView Question on Stackoverflow
Solution 1 - StringpeterSOView Answer on Stackoverflow
Solution 2 - StringBabaView Answer on Stackoverflow
Solution 3 - StringGlenn McElhoeView Answer on Stackoverflow
Solution 4 - StringPrabesh PView Answer on Stackoverflow
Solution 5 - Stringpr-palView Answer on Stackoverflow
Solution 6 - Stringamku91View Answer on Stackoverflow
Solution 7 - StringHardik BohraView Answer on Stackoverflow
Solution 8 - StringmonkrusView Answer on Stackoverflow
Solution 9 - StringKevin007View Answer on Stackoverflow