英文:
What's the go equivalent to PHP's list()?
问题
在PHP中,我们有list()
函数,它使我们能够在一次操作中将值分配给一组变量。例如:
list($a, $b) = ['valueA', 'valueB'];
echo $a; // valueA
echo $b; // valueB
在Go语言中是否有类似的功能?像Regexp.FindStringSubmatch()
这样的函数返回一个数组,所以直接将这些值映射到其他变量中会很方便。
英文:
In PHP we have the list()
which enable us to assign values to a list of variables in one operation. Eg:
<!-- language: lang-php -->
list($a, $b) = ['valueA', 'valueB'];
echo $a; # valueA
echo $b; # valueB
Is it possible do the same thing in Go? Functions like Regexp.FindStringSubmatch()
returns an array, so would be nice map this values directly into other variables.
答案1
得分: 3
你可以在Go语言中做不到这一点,但是有一种方法可以通过利用指针变量的值来实现。
创建一个函数,将所有接收器变量的指针作为切片传递,然后重新分配值。
func main() {
var arr = []string{"value 1", "value 2", "value 3"}
var a, b, c string
vcopy(arr, &a, &b, &c)
fmt.Println(a) // value 1
fmt.Println(b) // value 2
fmt.Println(c) // value 3
}
func vcopy(arr []string, dest ...*string) {
for i := range dest {
if len(arr) > i {
*dest[i] = arr[i]
}
}
}
通过使用这种技术,传递任何变量都不是问题。
示例:http://play.golang.org/p/gJzWp1WglJ
英文:
You cannot do that in go, but there is a way to achieve that by taking advantage the pointer value of it's variable.
Create a function, pass pointer of all receiver variables as slices, then re-assign the value.
func main() {
var arr = []string{"value 1", "value 2", "value 3"}
var a, b, c string
vcopy(arr, &a, &b, &c)
fmt.Println(a) // value 1
fmt.Println(b) // value 2
fmt.Println(c) // value 3
}
func vcopy(arr []string, dest ...*string) {
for i := range dest {
if len(arr) > i {
*dest[i] = arr[i]
}
}
}
Example http://play.golang.org/p/gJzWp1WglJ
By using this technique, passing any variables are not a problem.
答案2
得分: 1
没有内置的方法,但你可以编写自己的函数来实现类似的功能:
func unlist(x []string) (string, string) {
return x[0], x[1]
}
a, b := unlist(values);
然而,这意味着没有办法进行泛化,这意味着你必须为每个不同的参数数量和类型编写一个解构函数。
*注意:这个操作的通用名称是"解构赋值"。
英文:
There's nothing built-in but you can write your own function to do something similar:
func unlist(x []string) (string, string) {
return x[0], x[1]
}
a, b := unlist(values);
However, this does mean that there is no way to generalize this which means that you have to write a function for destructuring* every different number and type of argument you need it for.
*note: the general name for this operation is a "destructuring assignment".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论