Skip to content

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

Open
@abhinav

Description

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.

Activity

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

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions