Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple assignment from array or slice

Tags:

go

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.

like image 389
Kan Li Avatar asked Jul 29 '13 21:07

Kan Li


2 Answers

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:

  • LHS types match RHS types (in the first approximation).
  • The number of "homes" in LHS matches the number of "sources" (expression) in the RHS.

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.

like image 158
zzzz Avatar answered Nov 13 '22 12:11

zzzz


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)
}
like image 43
Zombo Avatar answered Nov 13 '22 12:11

Zombo