uber-go / guide

The Uber Go Style Guide.
Apache License 2.0
15.83k stars 1.71k forks source link

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

Open abhinav opened 1 year ago

abhinav commented 1 year ago

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 commented 1 year ago

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."