Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reflection cannot get the actual type of slice elements #43880

Closed
springrain opened this issue Jan 24, 2021 · 1 comment
Closed

Reflection cannot get the actual type of slice elements #43880

springrain opened this issue Jan 24, 2021 · 1 comment

Comments

@springrain
Copy link

springrain commented Jan 24, 2021

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

$ go version
go version go1.14 windows/amd64

Does this issue reproduce with the latest release?

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

go env Output
$ go env

set GO111MODULE=
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\caomei\AppData\Local\go-build
set GOENV=C:\Users\caomei\AppData\Roaming\go\env
set GOEXE=.exe
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=D:\golang\gopath
set GOPRIVATE=
set GOPROXY=https://goproxy.cn,direct
set GOROOT=D:\golang\goroot
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=D:\golang\goroot\pkg\tool\windows_amd64
set GCCGO=gccgo
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=C:\Users\caomei\AppData\Local\Temp\go-build318694546=/tmp/go-build -gno-record-gcc-switches

What did you do?

package zorm

import (
	"fmt"
	"reflect"
	"testing"
)

type sayHello interface {
	say()
}
type helloworld struct{}

func (entity helloworld) say() {
	fmt.Println("helloworld")
}

type helloSlice struct {
	hs []sayHello
}

func TestGetSliceElemType(t *testing.T) {

	hw := helloworld{}
	hslice := make([]sayHello, 0)
	hslice = append(hslice, hw)
	hs := helloSlice{hslice}

	rhs := reflect.ValueOf(hs).FieldByName("hs")

	elem := rhs.Type().Elem()
	fmt.Println(elem) // print is "zorm.sayHello" ,is sayHello interface
	if elem.String() != "zorm.helloworld" {
		t.Errorf("error:%v", "can not get real struct type --> zorm.helloworld")
	}

}

What did you expect to see?

I want to get the real type under slice zorm.helloworld

What did you see instead?

What I get is the interface type zorm.sayHello

@seankhliao
Copy link
Member

For questions please refer to https://github.com/golang/go/wiki/Questions

@golang golang locked and limited conversation to collaborators Jan 24, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants