登录
首页 >  Golang >  Go问答

go 中的 struct 变量

来源:stackoverflow

时间:2024-02-06 19:51:16 460浏览 收藏

大家好,今天本人给大家带来文章《go 中的 struct 变量》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

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

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

我找不到有关此案例的任何信息,我猜不包括此功能。对于这种情况有什么解决办法吗?


正确答案


相反,您可以使用键名称将数据放在地图上

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>