HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to split a string and assign it to variables

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
variableshowandsplitstringassign

Problem

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?

Solution

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 

Code Snippets

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)
}
127.0.0.1 5432
package main

import (
    "fmt"
    "net"
)

func main() {
    host, port, err := net.SplitHostPort("127.0.0.1:5432")
    fmt.Println(host, port, err)
}
127.0.0.1 5432 <nil>

Context

Stack Overflow Q#16551354, score: 277

Revisions (0)

No revisions yet.