Go to templates with eq and index

Go templates have some unexpected results when using eq with index for me. See this code:

 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}, }) } 

I expect a way out

 1 != 2 2 = 2 4 != 2 

but i get

 1 = 2 2 = 2 4 = 2 

What should I change to be able to compare array elements in go patterns?

+5
source share
2 answers

eq - prefix operation:

 {{if eq (index $n 0) (index $n 1)}}={{else}}!={{end}} 

Playground: http://play.golang.org/p/KEfXH6s7N1 .

+5
source

You are using the wrong operator and argument order. You must first write the operator, and then the operands:

 {{if eq (index $n 0) (index $n 1)}} 

This is more readable and convenient, since eq can take no more than two arguments, so you can write, for example:

 {{if eq (index $n 0) (index $n 1) (index $n 2)}} 

For simpler multi-level equality tests, eq (only) takes two or more arguments and compares the second and subsequent with the first, returning to the action

 arg1==arg2 || arg1==arg3 || arg1==arg4 ... 

(Unlike || in Go, however, eq is a function call, and all arguments will be evaluated.)

With this change, the output (try on the Go Playground ):

 1 != 2 2 = 2 4 != 2 

Note:

You do not need to enter the "loop" variable, the {{range}} action changes the point to the current element:

... a point is specified by consecutive elements of an array, slice or map ...

So you can simplify your template, this is equivalent to yours:

 {{range .}} {{index . 0}} {{if eq (index . 0) (index . 1)}}={{else}}!={{end}} {{index . 1}} {{end}} 

Also note that you can create variables in the template yourself, which is recommended if you use the same expression several times, which is nontrivial (for example, index . 0 ). This is also equivalent to your pattern:

 {{range .}}{{$0 := index . 0}}{{$1 := index . 1}} {{$0}} {{if eq $0 $1}}={{else}}!={{end}} {{$1}} {{end}} 

Also note that in this particular case, since the things that you want to output in the if and else branches also contain the = sign, you do not need two branches, = you need to output an additional sign in both cases ! if they are not equal. So, the following final template is also equivalent to yours:

 {{range .}}{{$0 := index . 0}}{{$1 := index . 1}} {{$0}} {{if ne $0 $1}}!{{end}}= {{$1}} {{end}} 
+3
source

Source: https://habr.com/ru/post/1234272/


All Articles