猿问

如何访问 Go 模板中的子字符串 (s[:2])?

类似于Go 模板:如何访问模板中的数组项 (arr[2])?
如何在 Go 模板中直接访问子字符串(例如 s[:2])?

每当我这样做时,我都会得到“坏字符 U+005B '['”

{{ .s[:2] }}


FFIVE
浏览 99回答 1
1回答

小唯快跑啊

你也可以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上尝试):世
随时随地看视频慕课网APP

相关分类

Go
我要回答