小唯快跑啊
你也可以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上尝试):世