snippetgoCritical
How to split a string and assign it to variables
Viewed 0 times
variableshowandsplitstringassign
Problem
In Python it is possible to split a string and assign it to variables:
but in Go it does not seem to work:
Question: How to split a string and assign values in one step?
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 = 1Question: How to split a string and assign values in one step?
Solution
Two steps, for example,
Output:
One step, for example,
Output:
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 5432One 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 5432package 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.