From befec5ddbbfbd81ec84e74e15a38044d67f8785b Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Wed, 14 Jun 2023 16:17:31 -0700 Subject: text/template: set variables correctly in range assignment I unintentionally flipped them in CL 446795. For #56490 Fixes #60801 Change-Id: I57586bec052e1b2cc61513870ce24dd6ce17e56b Reviewed-on: https://go-review.googlesource.com/c/go/+/503575 Reviewed-by: Ian Lance Taylor Run-TryBot: Ian Lance Taylor Reviewed-by: Rob Pike TryBot-Result: Gopher Robot Auto-Submit: Ian Lance Taylor Run-TryBot: Ian Lance Taylor Reviewed-by: Bryan Mills --- src/text/template/exec.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'src/text/template/exec.go') diff --git a/src/text/template/exec.go b/src/text/template/exec.go index fb60c17931..fd7db657d3 100644 --- a/src/text/template/exec.go +++ b/src/text/template/exec.go @@ -361,19 +361,27 @@ func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) { // mark top of stack before any variables in the body are pushed. mark := s.mark() oneIteration := func(index, elem reflect.Value) { - // Set top var (lexically the second if there are two) to the element. if len(r.Pipe.Decl) > 0 { if r.Pipe.IsAssign { - s.setVar(r.Pipe.Decl[0].Ident[0], elem) + // With two variables, index comes first. + // With one, we use the element. + if len(r.Pipe.Decl) > 1 { + s.setVar(r.Pipe.Decl[0].Ident[0], index) + } else { + s.setVar(r.Pipe.Decl[0].Ident[0], elem) + } } else { + // Set top var (lexically the second if there + // are two) to the element. s.setTopVar(1, elem) } } - // Set next var (lexically the first if there are two) to the index. if len(r.Pipe.Decl) > 1 { if r.Pipe.IsAssign { - s.setVar(r.Pipe.Decl[1].Ident[0], index) + s.setVar(r.Pipe.Decl[1].Ident[0], elem) } else { + // Set next var (lexically the first if there + // are two) to the index. s.setTopVar(2, index) } } -- cgit v1.3-5-g9baa