Is it possible in Go that unpack an array to multiple variables, like in Python.
For example
var arr [4]string = [4]string {"X", "Y", "Z", "W"}
x, y, z, w := arr
I found this is not supported in Go. Is there anything that I can do to avoid writing x,y,z,w=arr[0],arr[1],arr[2],arr[3]
More over, is it possible to support something like
var arr []string = [4]string {"X", "Y", "Z", "W"}
x, y, z, w := arr
Note it is now a slice instead of array, so compiler will implicitly check if len(arr)==4 and report error if not.
As you've correctly figured out, such constructs are not supported by Go. IMO, it's unlikely that they will ever be. Go designers prefer orthogonality for good reasons. For example, consider assignements:
The Python way of not valuing such principles might be somewhat practical here and there. But the cognitive load while reading large code bases is lower when the language follows the simple, regular patterns.
This is probably not what you had in mind, but it does offer a similar result:
package main
func unpack(src []string, dst ...*string) {
for ind, val := range dst {
*val = src[ind]
}
}
func main() {
var (
a = []string{"X", "Y", "Z", "W"}
x, y, z, w string
)
unpack(a, &x, &y, &z, &w)
println(x, y, z, w)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With