英文:
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}]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论