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