亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

訪問切片 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 關注
  • 225 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號