類似于Go 模板:如何訪問模板中的陣列項 (arr[2])?
如何在 Go 模板中直接訪問子字串(例如 s[:2])?
每當我這樣做時,我都會得到“壞字符 U 005B '['”
{{ .s[:2] }}
uj5u.com熱心網友回復:
你也可以slice在 s 上使用模板函式string(它是在Go 1.13中添加的):
模板功能:
slice slice returns the result of slicing its first argument by the remaining arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2], while "slice x" is x[:], "slice x 1" is x[1:], and "slice x 1 2 3" is x[1:2:3]. The first argument must be a string, slice, or array.
例如:
t := template.Must(template.New("").Parse(`{{ slice . 0 2 }}`))
if err := t.Execute(os.Stdout, "abcdef"); err != nil {
panic(err)
}
這將輸出(在Go Playground上嘗試):
ab
不要忘記 Go 字串存盤的是 UTF-8 編碼的位元組序列,而索引和切片字串使用位元組索引(而不是rune索引)。當字串包含多位元組符文時,這很重要,如下例所示:
t := template.Must(template.New("").Parse(`{{ slice . 0 3 }}`))
if err := t.Execute(os.Stdout, "世界"); err != nil {
panic(err)
}
這將輸出一個(在Go Playgroundrune上嘗試):
世
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/414524.html
標籤:
上一篇:GoogleDriveAPI錯誤-“訊息”:“找不到共享驅動器:xyz”
下一篇:使用嵌入式結構的建構式實體化結構
