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

访问切片 Golang 模板中的结构中的特定字段

访问切片 Golang 模板中的结构中的特定字段

Go
慕工程0101907 2022-05-23 16:41:26
我有这样的地方我发送到模板年数据(这是结构的切片)。如何AcaYear仅访问第二项(结构)的模板侧字段?整个第二项我可以访问为{{index . 1 }}. 我还可以在切片上进行范围并获取AcaYear所有项目的字段。但只需要AcaYear第二项的字段(结果应该是2021-2022)。package mainimport (    "log"    "os"    "text/template")type course struct {    Number string    Name   string    Units  string}type semester struct {    Term    string    Courses []course}type year struct {    AcaYear string    Fall    semester    Spring  semester    Summer  semester}var tpl *template.Templatefunc init() {    tpl = template.Must(template.ParseFiles("tpl.gohtml"))}func main() {    years := []year{        year{            AcaYear: "2020-2021",            Fall: semester{                Term: "Fall",                Courses: []course{                    course{"CSCI-40", "Introduction to Programming in Go", "4"},                    course{"CSCI-130", "Introduction to Web Programming with Go", "4"},                    course{"CSCI-140", "Mobile Apps Using Go", "4"},                },            },            Spring: semester{                Term: "Spring",                Courses: []course{                    course{"CSCI-50", "Advanced Go", "5"},                    course{"CSCI-190", "Advanced Web Programming with Go", "5"},                    course{"CSCI-191", "Advanced Mobile Apps With Go", "5"},                },            },        },        year{            AcaYear: "2021-2022",            Fall: semester{                Term: "Fall",                Courses: []course{                    course{"CSCI-40", "Introduction to Programming in Go", "4"},                    course{"CSCI-130", "Introduction to Web Programming with Go", "4"},                    course{"CSCI-140", "Mobile Apps Using Go", "4"},                },            },
查看完整描述

1 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

只需对index调用进行分组并将.AcaYear字段选择器应用于结果:

{{ (index . 1).AcaYear }}

这将输出(在Go Playground上尝试):

2021-2022


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

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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