PHP的list()等效于什么? [重复]

This question already has an answer here:

In PHP we have the list() which enable us to assign values to a list of variables in one operation. Eg:

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.

</div>

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.

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".