Are dynamic variables supported?

不羁的心 提交于 2020-05-23 08:16:07

问题


I was wondering if it is possible to dynamically create variables in Go?

I have provided a pseudo-code below to illustrate what I mean. I am storing the newly created variables in a slice:

func method() {
  slice := make([]type)
  for(i=0;i<10;i++)
  {
    var variable+i=i;
    slice := append(slice, variablei)
  }
}

At the end of the loop, the slice should contain the variables: variable1, variable2...variable9


回答1:


Go has no dynamic variables. Dynamic variables in most languages are implemented as Map (Hashtable).

So you can have one of following maps in your code that will do what you want

var m1 map[string]int 
var m2 map[string]string 
var m3 map[string]interface{}

here is Go code that does what you what

http://play.golang.org/p/d4aKTi1OB0

package main

import "fmt"


func method() []int {
  var  slice []int 
  for i := 0; i < 10; i++  {
    m1 := map[string]int{}
    key := fmt.Sprintf("variable%d", i)
    m1[key] = i
    slice = append(slice, m1[key])
  }
  return slice
}

func main() {
    fmt.Println(method())
}



回答2:


No; you cannot refer to local variables if you don’t know their names at compile-time.

If you need the extra indirection you can do it using pointers instead.

func function() {
    slice := []*int{}
    for i := 0; i < 10; i++ {
        variable := i
        slice = append(slice, &variable)
    }
    // slice now contains ten pointers to integers
}

Also note that the parentheses in the for loop ought to be omitted, and putting the opening brace on a new line is a syntax error due to automatic semicolon insertion after ++. makeing a slice requires you to pass a length, hence I don’t use it since append is used anyway.



来源:https://stackoverflow.com/questions/21147978/are-dynamic-variables-supported

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!