是否支持动态变量?

编程入门 行业动态 更新时间:2024-10-23 07:20:52
本文介绍了是否支持动态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道是否可以在Go中动态创建变量?

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) } }

在循环结束时,切片应包含以下变量:variable1,variable2 ... variable9

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

推荐答案

Go has没有动态变量。 大多数语言中的动态变量都实现为Map(哈希表)。

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{}

这里的Go代码可以完成您的工作

here is Go code that does what you what

play.golang/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()) }

更多推荐

是否支持动态变量?

本文发布于:2023-11-28 07:26:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641467.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!