为了账号安全,请及时绑定邮箱和手机立即绑定

从嵌套结构中检索值

从嵌套结构中检索值

Go
侃侃无极 2022-07-04 16:54:51
我正在尝试从 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}
查看完整描述

1 回答

?
呼唤远方

TA贡献1856条经验 获得超11个赞

您创建的“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}}, }

此外,您的结构字段名称也存在一些不一致;创建实例时也应使用定义期间使用的字段名称,否则您将收到错误消息。


查看完整回答
反对 回复 2022-07-04
  • 1 回答
  • 0 关注
  • 151 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号