使用eq和index转到模板

Ond*_*dra 7 go go-templates

eqindex我一起使用时,Go模板有一些意想不到的结果.看到这段代码:

package main

import (
    "os"
    "text/template"
)

func main() {
    const myTemplate = `
{{range $n := .}}
    {{index $n 0}} {{if (index $n 0) eq (index $n 1)}}={{else}}!={{end}} {{index $n 1}}
{{end}}
`
    t := template.Must(template.New("").Parse(myTemplate))

    t.Execute(os.Stdout,
        [][2]int{
            [2]int{1, 2},
            [2]int{2, 2},
            [2]int{4, 2},
        })

}
Run Code Online (Sandbox Code Playgroud)

我希望有输出

1 != 2
2 = 2
4 != 2
Run Code Online (Sandbox Code Playgroud)

但我明白了

1 = 2
2 = 2
4 = 2
Run Code Online (Sandbox Code Playgroud)

我应该更改什么才能比较go模板中的数组成员?

Ain*_*r-G 8

eq 是前缀操作:

{{if eq (index $n 0) (index $n 1)}}={{else}}!={{end}}
Run Code Online (Sandbox Code Playgroud)

游乐场:http://play.golang.org/p/KEfXH6s7N1.


icz*_*cza 7

您使用了错误的运算符和参数顺序。您必须先编写运算符,然后编写操作数:

{{if eq (index $n 0) (index $n 1)}}
Run Code Online (Sandbox Code Playgroud)

这更具可读性和方便性,因为eq可以采用多个参数,因此您可以编写例如:

{{if eq (index $n 0) (index $n 1) (index $n 2)}}
Run Code Online (Sandbox Code Playgroud)

对于更简单的多路相等测试, eq (仅)接受两个或多个参数,并将第二个和后续的参数与第一个进行比较,返回有效

arg1==arg2 || arg1==arg3 || arg1==arg4 ...
Run Code Online (Sandbox Code Playgroud)

(然而,与 Go 中的 || 不同,eq 是一个函数调用,并且所有参数都将被求值。)

通过此更改输出(在Go Playground上尝试):

1 != 2

2 = 2

4 != 2
Run Code Online (Sandbox Code Playgroud)

笔记:

您不需要引入“循环”变量,该{{range}}操作将点更改为当前项目:

...点设置为数组、切片或映射的连续元素...

所以你可以简化你的模板,这相当于你的:

{{range .}}
    {{index . 0}} {{if eq (index . 0) (index . 1)}}={{else}}!={{end}} {{index . 1}}
{{end}}
Run Code Online (Sandbox Code Playgroud)

另请注意,您可以自己在模板中创建变量,如果您多次使用相同的表达式(例如index . 0),则建议您这样做。这也相当于您的模板:

{{range .}}{{$0 := index . 0}}{{$1 := index . 1}}
    {{$0}} {{if eq $0 $1}}={{else}}!={{end}} {{$1}}
{{end}}
Run Code Online (Sandbox Code Playgroud)

if另请注意,在这种特定情况下,由于您要在和else分支中输出的内容都包含=符号,因此您不需要 2 个分支,=需要在两种情况下都输出,!如果它们不相等,则只需要一个额外的符号。因此,以下最终模板也与您的模板等效:

{{range .}}{{$0 := index . 0}}{{$1 := index . 1}}
    {{$0}} {{if ne $0 $1}}!{{end}}= {{$1}}
{{end}}
Run Code Online (Sandbox Code Playgroud)