diff options
| author | Nathan Nguyen <nhan13574@gmail.com> | 2025-12-05 15:50:24 -0500 |
|---|---|---|
| committer | Sean Liao <sean@liao.dev> | 2025-12-15 09:04:58 -0800 |
| commit | b7944a5f80b5aa7ad43730064cf4ebc8c473df47 (patch) | |
| tree | 73fb7579a3739f294df81f087f84928e3d0c237e | |
| parent | 6713f46426c70f601ac33471d16be7b0e1aae349 (diff) | |
| download | go-b7944a5f80b5aa7ad43730064cf4ebc8c473df47.tar.xz | |
text/template: fix slice builtin for pointers to arrays
The slice function now properly handles pointers to arrays by calling
indirect() to dereference pointers, matching the behavior of the index
function.
Fixes #39596
Change-Id: Id4920edbfd8fd3df3a181b59a61733f88b0f104d
Reviewed-on: https://go-review.googlesource.com/c/go/+/727400
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Sean Liao <sean@liao.dev>
Reviewed-by: Rob Pike <r@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
| -rw-r--r-- | src/text/template/exec_test.go | 7 | ||||
| -rw-r--r-- | src/text/template/funcs.go | 4 |
2 files changed, 10 insertions, 1 deletions
diff --git a/src/text/template/exec_test.go b/src/text/template/exec_test.go index 8665f3ad49..5812c7b136 100644 --- a/src/text/template/exec_test.go +++ b/src/text/template/exec_test.go @@ -43,7 +43,8 @@ type T struct { SIEmpty []int SB []bool // Arrays - AI [3]int + AI [3]int + PAI *[3]int // pointer to array // Maps MSI map[string]int MSIone map[string]int // one element, for deterministic output @@ -142,6 +143,7 @@ var tVal = &T{ SI: []int{3, 4, 5}, SICap: make([]int, 5, 10), AI: [3]int{3, 4, 5}, + PAI: &[3]int{3, 4, 5}, SB: []bool{true, false}, MSI: map[string]int{"one": 1, "two": 2, "three": 3}, MSIone: map[string]int{"one": 1}, @@ -556,6 +558,9 @@ var execTests = []execTest{ {"array[:]", "{{slice .AI}}", "[3 4 5]", tVal, true}, {"array[1:]", "{{slice .AI 1}}", "[4 5]", tVal, true}, {"array[1:2]", "{{slice .AI 1 2}}", "[4]", tVal, true}, + {"pointer to array[:]", "{{slice .PAI}}", "[3 4 5]", tVal, true}, + {"pointer to array[1:]", "{{slice .PAI 1}}", "[4 5]", tVal, true}, + {"pointer to array[1:2]", "{{slice .PAI 1 2}}", "[4]", tVal, true}, {"string[:]", "{{slice .S}}", "xyz", tVal, true}, {"string[0:1]", "{{slice .S 0 1}}", "x", tVal, true}, {"string[1:]", "{{slice .S 1}}", "yz", tVal, true}, diff --git a/src/text/template/funcs.go b/src/text/template/funcs.go index 30b3243a5a..ed9c7ea5d5 100644 --- a/src/text/template/funcs.go +++ b/src/text/template/funcs.go @@ -244,6 +244,10 @@ func slice(item reflect.Value, indexes ...reflect.Value) (reflect.Value, error) if !item.IsValid() { return reflect.Value{}, fmt.Errorf("slice of untyped nil") } + var isNil bool + if item, isNil = indirect(item); isNil { + return reflect.Value{}, fmt.Errorf("slice of nil pointer") + } if len(indexes) > 3 { return reflect.Value{}, fmt.Errorf("too many slice indexes: %d", len(indexes)) } |
