Multiple assignment from array or slice

Is it possible in Go to unpack an array into several variables, for example, in Python.

for instance

var arr [4]string = [4]string {"X", "Y", "Z", "W"} x, y, z, w := arr 

I found that this is not supported in Go. Is there anything I can do to not write x,y,z,w=arr[0],arr[1],arr[2],arr[3]

Moreover, is it possible to maintain something like

 var arr []string = [4]string {"X", "Y", "Z", "W"} x, y, z, w := arr 

Note that now this is a fragment instead of an array, so the compiler will implicitly check if len (arr) == 4 and report an error if not.

+4
source share
1 answer

As you understand, such designs are not supported by Go. IMO, they are unlikely to ever be. Go designers prefer orthogonality for good reason. For example, consider the destination:

  • LHS types correspond to RHS types (to a first approximation).
  • The number of β€œhouses” in the LHS corresponds to the number of β€œsources” (expression) in the RHS.

Python's way of not evaluating such principles can be somewhat practical here and there. But the cognitive load when reading large base codes is lower when the language follows simple regular patterns.

+3
source

Source: https://habr.com/ru/post/1494148/


All Articles