Go语言中的变量命名结构

izkcnapc  于 2023-03-21  发布在  Go
关注(0)|答案(1)|浏览(127)

我怎样才能得到这个输出?

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

我找不到任何关于这种情况的信息,我猜这个功能不包括在内。这种情况有什么解决方案吗?

klh5stk1

klh5stk11#

相反,您可以使用键名将数据放置在Map上

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

相关问题