Skip to content

text/template: slice function does not work when value is wrapped in interface #36199

@icza

Description

@icza

What version of Go are you using (go version)?

$ go version
go version go1.13.3 linux/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/icza/.cache/go-build"
GOENV="/home/icza/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GONOPROXY="xxx"
GONOSUMDB="xxx"
GOOS="linux"
GOPATH="/home/icza/gows"
GOPRIVATE="xxx"
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build339874310=/tmp/go-build -gno-record-gcc-switches"

What did you do?

Tried to use the slice template function introduced in Go 1.13.

Playground:

t := template.Must(template.New("").Parse(`{{slice .x 0 2}}`))

m1 := map[string][]int{
	"x": []int{1, 2, 3, 4},
}
fmt.Println(t.Execute(os.Stdout, m1))

m2 := map[string]interface{}{
	"x": []int{1, 2, 3, 4},
}
fmt.Println(t.Execute(os.Stdout, m2))

It only works if value is not wrapped in an interface value (e.g. interface{}). In my opinion, a concrete slice value stored in an interface should be "extracted" and used.

What did you expect to see?

[1 2]<nil>
[1 2]<nil>

What did you see instead?

[1 2]<nil>
template: :1:2: executing "" at <slice .x 0 2>: error calling slice: reflect: call of reflect.Value.Slice on interface Value

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions