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

proposal: Avoid calling methods on map value, e.g. m[key].Method() #178

Open
abhinav opened this issue Apr 7, 2023 · 1 comment
Open

Comments

@abhinav
Copy link
Collaborator

abhinav commented Apr 7, 2023

Follow up to https://github.com/uber-go/guide/pull/170/files/6387abd06dabaa78a387a96825a7ec2a9ae716af#r1160263742

In-short:

m[key].Method() where you don't control map keys fully, and can't be certain that the value exists, will make it easy to panic or operate on invalid values. e..g if map[T]Foo with a value receiver, m[key].Method() will operate on the zero value of Foo, which may not be desirable. And given map[T]*Foo, m[key].Method() will operate on nil, which Method() likely doesn't handle unless explicitly specified and planned.

I don't think we should forbid it outright because when you do explicitly have the zero-value-behavior (nil if pointer) in mind, m[key].Method() is more readable than:

if v, ok := m[key]; ok {
  v.Method()   
}

CC @peterbourgon who brought this up in #170.

@peterbourgon
Copy link

Yeah, I think it's enough to say something like "If you know that the map value exists, or gracefully handle nil method receivers, then it is possible to call m[key].Method() safely."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants