来自数组或切片的多重分配 [英] multiple assignment from array or slice

查看:38
本文介绍了来自数组或切片的多重分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中是否可以像在Python中那样将数组解压缩为多个变量.

Is it possible in Go that unpack an array to multiple variables, like in Python.

例如

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

我发现Go不支持此功能.有什么我可以避免写 x,y,z,w = arr [0],arr [1],arr [2],arr [3]

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

请注意,它现在是切片而不是数组,因此编译器将隐式检查len(arr)== 4并报告错误.

Note it is now a slice instead of array, so compiler will implicitly check if len(arr)==4 and report error if not.

推荐答案

正如您已经正确理解的那样,Go不支持此类构造.海事组织,它们不可能成为现实.Go设计师出于充分的理由偏爱正交性.例如,考虑分配:

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类型与RHS类型匹配(在第一近似中).
  • LHS中房屋"的数量与RHS中来源"(表达)的数量相匹配.

Python不重视这些原理的方法在这里和那里可能都是实用的.但是,当语言遵循简单,规​​则的模式时,在读取大型代码库时的认知负担就会降低.

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.

这篇关于来自数组或切片的多重分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆