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

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

variable named struct in go

问题

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

如何获得这个输出?

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

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

英文:

how can i get this output?

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

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

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

  1. type datas struct {
  2. age int
  3. height int
  4. weight int
  5. }
  6. func main(){
  7. structMap := make(map[string]interface{})
  8. age := 5
  9. height := 10
  10. weight := 15
  11. namelist := []string{"b", "c", "d"}
  12. for count, val := range namelist {
  13. count = count + 1 // 这是因为你期望的输出
  14. out := datas{age+count, height+count, weight+count}
  15. structMap[val] = out
  16. }
  17. fmt.Println(structMap)
  18. // 输出: map[b:{6 11 16} c:{7 12 17} d:{8 13 18}]
  19. }

希望对你有帮助!

英文:

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

  1. type datas struct {
  2. age int
  3. height int
  4. weight int
  5. }
  6. func main(){
  7. structMap := make(map[string]interface{})
  8. age := 5
  9. height := 10
  10. weight := 15
  11. namelist := []string{"b", "c", "d"}
  12. for count, val := range namelist {
  13. count = count + 1 // this is due to your expected output
  14. out := datas{age+count,height+count,weight+count}
  15. structMap[val] = out
  16. }
  17. fmt.Println(structMap)
  18. // output: map[b:{6 11 16} c:{7 12 17} d:{8 13 18}]
  19. }

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:

确定