Skip to content

reflect: support array pointer in Value.Len()  #52411

@Antonboom

Description

@Antonboom

Hello!

Docs says:

package builtin

// The len built-in function returns the length of v, according to its type:
//	...
//	Pointer to array: the number of elements in *v (even if v is nil).
//	...
func len(v Type) int

But reflect doesn't support it:

package reflect

// Len returns v's length.
// It panics if v's Kind is not Array, Chan, Map, Slice, or String.
func (v Value) Len() int {
	k := v.kind()
	switch k {                 // <-- No array ptr case!
	case Array: /* ... */
	case Chan: /* ... */
	case Map: /* ... */
	case Slice: /* ... */
	case String: /* ... */
        }
	panic(&ValueError{"reflect.Value.Len", v.kind()})
}

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

$ go version
go version go1.18 darwin/arm64

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="on"
GOARCH="arm64"
GOBIN="/Users/anthony/golang_workspace/bin"
GOCACHE="/Users/anthony/Library/Caches/go-build"
GOENV="/Users/anthony/Library/Application Support/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="arm64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/anthony/golang_workspace/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/anthony/golang_workspace"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_arm64"
GOVCS=""
GOVERSION="go1.18"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/dev/null"
GOWORK=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -arch arm64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/6t/v80c8sfs5zqf38b2yhzq592h0000gn/T/go-build3171440032=/tmp/go-build -gno-record-gcc-switches -fno-common"

What did you do?

https://go.dev/play/p/8rAZrY3A-yJ

package main

import (
	"fmt"
	"reflect"
)

func main() {
	a := [3]int{1, 2, 3}
	fmt.Println(len(a))
	fmt.Println(reflect.ValueOf(a).Len())

	aPtr := &a
	fmt.Println(len(aPtr))
	fmt.Println(reflect.ValueOf(aPtr).Len()) // panic!
}

What did you expect to see?

3
3
3
3

What did you see instead?

3
3
3
panic: reflect: call of reflect.Value.Len on ptr Value

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions