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

reflect.Value.MethodByName is not returning zero value when not found #39307

Closed
kstenerud opened this issue May 28, 2020 · 3 comments
Closed

Comments

@kstenerud
Copy link

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

play.golang.org

Does this issue reproduce with the latest release?

Yes

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

play.golang.org

What did you do?

https://play.golang.org/p/Rnjm3-DT5Il

package main

import (
	"fmt"
	"reflect"
)

func main() {
	v := reflect.ValueOf(1)
	m := v.MethodByName("String")
	if !m.IsValid() {
		fmt.Println("Invalid")
	}
	if m.IsZero() {
		fmt.Println("Zero")
	}
}

What did you expect to see?

Zero

What did you see instead?

Invalid
panic: reflect: call of reflect.Value.IsZero on zero Value

goroutine 1 [running]:
reflect.Value.IsZero(0x0, 0x0, 0x0, 0x1)
	/usr/local/go-faketime/src/reflect/value.go:1111 +0x4b6
main.main()
	/tmp/sandbox851150891/prog.go:14 +0xf1

According to https://golang.org/pkg/reflect/#Value.MethodByName "It returns the zero Value if no method was found."

@ianlancetaylor
Copy link
Contributor

The zero Value is not the value for which the IsZero method returns true; it is the Value for which the IsValid method returns false. See the docs for IsValid, which say "It returns false if v is the zero Value." See also the docs for Value, which say "The zero Value represents no value. Its IsValid method returns false, its Kind method returns Invalid, its String method returns "", and all other methods panic. "

@kstenerud
Copy link
Author

That's incredibly confusing, having a "zero" value that panics on IsZero(). Surely there's a more elegant way to structure the API?

@ianlancetaylor
Copy link
Contributor

Well, perhaps there is. Too late now, though, per https://golang.org/doc/go1compat.

@golang golang locked and limited conversation to collaborators May 29, 2021
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