Skip to content

reflect: type of an interface is nil #35427

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

Closed
kindermoumoute opened this issue Nov 7, 2019 · 1 comment
Closed

reflect: type of an interface is nil #35427

kindermoumoute opened this issue Nov 7, 2019 · 1 comment

Comments

@kindermoumoute
Copy link

I am trying to understand why this code works:

ioReaderType := reflect.ValueOf(struct{ ioReader io.Reader }{}).FieldByName("ioReader").Type()
fmt.Println(ioReaderType.String()) // prints "io.Reader"

But this one panic

ioReaderType := reflect.TypeOf(io.Reader(nil))
fmt.Println(ioReaderType.String()) // panic

https://play.golang.org/p/F2ndRax1f4E

@randall77
Copy link
Contributor

From the doc of reflect.TypeOf:

TypeOf returns the reflection Type that represents the dynamic type of i. If i is a nil interface value, TypeOf returns nil.

io.Reader(nil) is a nil interface value. Castingnil to an interface type is still nil.

See the example for reflect.TypeOf. You want to instead do:

reflect.TypeOf((*io.Reader)(nil)).Elem()

Casting a nil pointer to an interface type is not nil.

@golang golang locked and limited conversation to collaborators Nov 6, 2020
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