从嵌套结构中检索值

我正在尝试从 golang 中的嵌套结构访问值。我的最终结构如下


StudentDetails = [{"rollno":3,"name":"John","score":{"sub1":50,"sub2":48,"sub3":45}} , {"rollno":4,"name":"James","score":{"sub1":38,"sub2":35,"sub3":40}}]

我想单独打印这些值。为此,我尝试添加一个循环


for i, details  := range StudentDetails {


    glog.Info("increment ", i)

    glog.Info("name of student ", details.name)

    glog.Info("mark of sub 1", details.score.sub1)

}

但我总是得到错误


"(type map[string]interface {} has no field or method name"" 我的结构如下


type scoreCard struct {

    subject1                int     `json:"id"`

    subject2                int     `json:"id"`

    subject3                int     `json:"id"`


}


type StudDetails    struct {


    roll int

    name string

    score scoreCard

}


侃侃无极
浏览 152回答 1
1回答

呼唤远方

您创建的“StudentDetails”变量属于 map 类型。我想你打算做的是这个var StudentDetails = []StudDetails{ {"roll":3,"name":"John","score":{"subject1":50,"subject2":48,"subject3":45}}, {"roll":4,"name":"James","score":{"subject1":38,"subject2":35,"subject3":40}}, }此外,您的结构字段名称也存在一些不一致;创建实例时也应使用定义期间使用的字段名称,否则您将收到错误消息。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go