Reputation: 1935
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?
Upvotes: 168
Views: 166892
Reputation: 183
**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
}
Upvotes: 1
Reputation: 3558
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...)
Upvotes: 3
Reputation: 1688
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", ","))
}
Upvotes: 1
Reputation: 185
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>
Upvotes: 9
Reputation: 61
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])
Upvotes: 1
Reputation: 150
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) }
Upvotes: 2
Reputation: 1038
There's are multiple ways to split a string :
_
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)
Split based on struct :
_
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.
Upvotes: 1
Reputation: 95161
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
}
Upvotes: 21
Reputation: 166915
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>
Upvotes: 277