Go语言中与PHP的list()函数相对应的是什么?

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

What's the go equivalent to PHP's list()?

问题

在PHP中,我们有list()函数,它使我们能够在一次操作中将值分配给一组变量。例如:

  1. list($a, $b) = ['valueA', 'valueB'];
  2. echo $a; // valueA
  3. 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 -->

  1. list($a, $b) = [&#39;valueA&#39;, &#39;valueB&#39;];
  2. echo $a; # valueA
  3. 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语言中做不到这一点,但是有一种方法可以通过利用指针变量的值来实现。

创建一个函数,将所有接收器变量的指针作为切片传递,然后重新分配值。

  1. func main() {
  2. var arr = []string{"value 1", "value 2", "value 3"}
  3. var a, b, c string
  4. vcopy(arr, &a, &b, &c)
  5. fmt.Println(a) // value 1
  6. fmt.Println(b) // value 2
  7. fmt.Println(c) // value 3
  8. }
  9. func vcopy(arr []string, dest ...*string) {
  10. for i := range dest {
  11. if len(arr) > i {
  12. *dest[i] = arr[i]
  13. }
  14. }
  15. }

通过使用这种技术,传递任何变量都不是问题。

示例: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.

  1. func main() {
  2. var arr = []string{&quot;value 1&quot;, &quot;value 2&quot;, &quot;value 3&quot;}
  3. var a, b, c string
  4. vcopy(arr, &amp;a, &amp;b, &amp;c)
  5. fmt.Println(a) // value 1
  6. fmt.Println(b) // value 2
  7. fmt.Println(c) // value 3
  8. }
  9. func vcopy(arr []string, dest ...*string) {
  10. for i := range dest {
  11. if len(arr) &gt; i {
  12. *dest[i] = arr[i]
  13. }
  14. }
  15. }

Example http://play.golang.org/p/gJzWp1WglJ

By using this technique, passing any variables are not a problem.

答案2

得分: 1

没有内置的方法,但你可以编写自己的函数来实现类似的功能:

  1. func unlist(x []string) (string, string) {
  2. return x[0], x[1]
  3. }
  4. a, b := unlist(values);

然而,这意味着没有办法进行泛化,这意味着你必须为每个不同的参数数量和类型编写一个解构函数。

*注意:这个操作的通用名称是"解构赋值"。

英文:

There's nothing built-in but you can write your own function to do something similar:

  1. func unlist(x []string) (string, string) {
  2. return x[0], x[1]
  3. }
  4. 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".

huangapple
  • 本文由 发表于 2016年4月26日 12:27:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/36855264.html
匿名

发表评论

匿名网友

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

确定