1 回答
TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
你也可以slice在 s 上使用模板函數(shù)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 字符串存儲(chǔ)的是 UTF-8 編碼的字節(jié)序列,而索引和切片字符串使用字節(jié)索引(而不是rune索引)。當(dāng)字符串包含多字節(jié)符文時(shí),這很重要,如下例所示:
t := template.Must(template.New("").Parse(`{{ slice . 0 3 }}`))
if err := t.Execute(os.Stdout, "世界"); err != nil {
panic(err)
}
這將輸出一個(gè)(在Go Playgroundrune上嘗試):
世
- 1 回答
- 0 關(guān)注
- 140 瀏覽
添加回答
舉報(bào)
