dsgwdigu84950 2014-01-15 20:54
浏览 30
已采纳

GOlang:动态变量

I'm new to GO and 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

Thank you for your help!!

  • 写回答

2条回答 默认 最新

  • dsbj66959 2014-01-15 21:08
    关注

    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())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里