在Go语言中,变量名为`struct`。

huangapple go评论80阅读模式
英文:

variable named struct in go

问题

你好!以下是你要翻译的内容:

如何获得这个输出?

type datas struct {
    age int
    height int
    weight int
}
func main(){
    var age := 5
    var height := 10
    var weight := 15
    namelist := []string{"b", "c", "d"}
    for count, a := range namelist {
        a := datas{age+count,height+count,weight+count}
	//期望输出: b{6,11,16} , c{7,12,17}, d{8,13,18}
    }
}

我找不到关于这个情况的任何信息,我猜测这个功能可能没有包含在内。对于这种情况,是否有任何解决方案?

英文:

how can i get this output?

type datas struct {
    age int
    height int
    weight int
}
func main(){
    var age := 5
    var height := 10
    var weight := 15
    namelist := []string{"b", "c", "d"}
    for count, a := range namelist {
        a := datas{age+count,height+count,weight+count}
	//Expected Output: b{6,11,16} , c{7,12,17}, d{8,13,18}
    }
}

I can't find anything about this case and I guess this feature is not included. Is there any solution for this situation?

答案1

得分: 0

你可以将数据放在一个带有键名的地图上。

type datas struct {
    age int
    height int
    weight int
}

func main(){
    structMap := make(map[string]interface{})
    age := 5
    height := 10
    weight := 15
    namelist := []string{"b", "c", "d"}
    for count, val := range namelist {
        count = count + 1 // 这是因为你期望的输出
        out := datas{age+count, height+count, weight+count}
        structMap[val] = out
    }

    fmt.Println(structMap)
    // 输出: map[b:{6 11 16} c:{7 12 17} d:{8 13 18}]
}

希望对你有帮助!

英文:

Instead, you can put your data on a map with the key name

type datas struct {
    age int
    height int
    weight int
}
func main(){
	structMap := make(map[string]interface{})
    age := 5
    height := 10
    weight := 15
    namelist := []string{"b", "c", "d"}
    for count, val := range namelist {
		count = count + 1 // this is due to your expected output
        out := datas{age+count,height+count,weight+count}
		structMap[val] = out
    }

	fmt.Println(structMap)
    // output: map[b:{6 11 16} c:{7 12 17} d:{8 13 18}]
}

huangapple
  • 本文由 发表于 2023年3月16日 17:58:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75754585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定