Kan Li
Kan Li

Reputation: 8797

multiple assignment from array or slice

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.

Upvotes: 10

Views: 7096

Answers (2)

Zombo
Zombo

Reputation: 1

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)
}

Upvotes: 5

zzzz
zzzz

Reputation: 91253

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.

Upvotes: 6

Related Questions