如何打开切片

How can i unpack a slice in golang?

I have a slice,

var a = [1,2,3,4,5, ...n ]

What i want to achieve is to be able to generate new variables dynamically for the length of the slice. The output should look something like this

Var a = 1, b= 2, c=3, n=last number in slice

I am considering that the thing you want is dynamic variable allocation. I guess you cannot do so. Instead you can use Go Map to store your data as key-value format.

func main() {
    mySlice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    myVariables := make(map[string]int)
    ch := 'a'
    for _, value := range mySlice {
        key := fmt.Sprintf("%c", ch)
        myVariables[key] = value
        ch++
    }
    fmt.Println(myVariables)
}

The output will be:

map[a:1 b:2 c:3 d:4 e:5 f:6 g:7 h:8 i:9 j:10]

You can also generate the key name randomly, visit here for details