1 回答

TA贡献1863条经验 获得超2个赞
你也可以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上尝试):
世
- 1 回答
- 0 关注
- 98 浏览
添加回答
举报