从数组或切片进行多重赋值

huangapple go评论67阅读模式
英文:

multiple assignment from array or slice

问题

在Go语言中,不能像Python那样将数组解包给多个变量。但是,你可以使用索引来避免编写x, y, z, w = arr[0], arr[1], arr[2], arr[3]这样的代码。

此外,对于切片(slice),你可以这样写:

var arr []string = []string{"X", "Y", "Z", "W"}
x, y, z, w := arr[0], arr[1], arr[2], arr[3]

请注意,这里的arr是一个切片而不是数组,因此编译器会隐式检查len(arr)==4,如果不满足条件会报错。

英文:

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.

答案1

得分: 5

正如你正确地发现的那样,Go语言不支持这样的结构。在我看来,它们很可能永远不会被支持。Go的设计者更喜欢正交性,有很好的理由。例如,考虑赋值操作:

  • 左侧的类型与右侧的类型匹配(在第一次近似中)。
  • 左侧的“目标”数量与右侧的“源”(表达式)数量匹配。

在某些情况下,Python不遵循这些原则可能会有一定的实用性。但是,当阅读大型代码库时,语言遵循简单、规律的模式时,认知负荷会更低。

英文:

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.

答案2

得分: 5

这可能不是你想要的,但它提供了类似的结果:

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)
}
英文:

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

huangapple
  • 本文由 发表于 2013年7月30日 05:33:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/17934611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定