Skip to content

cmd/vet: warn about changing fields in non-escaping variables if they are not set after assignment #28099

Description

@driusan

It's a common mistake for new users of Go* to accidentally attempt to set a field on a non-pointer receiver.

For instance:

type Something struct{
     Done bool
}

func (s Something) Bar() {
     if s.Done {
         return
     }
     // Code goes here
     s.Done = true
}

The above is legal in Go 1.x because s is passed by value to Bar, but the change only lasts for the duration of the function call since the local version on the stack was modified, not the value which the method was called on. This is almost always a bug and I can't think of any situations where that would be the intention of the programmer when attempting to set a property inside of a method.

This proposal is to make it illegal to modify a property on a receiver when the receiver is passed-by value. Arguments other than the receiver would unaffected.

This could be done either as ago vet check in Go 1.x, or a language change in Go2.

  • I don't have any numbers to support this claim, but blaming new users means I wouldn't need to admit if it were to theoretically be a mistake that I might still occasionally make.

Metadata

Metadata

Assignees

No one assigned

    Labels

    AnalysisIssues related to static analysis (vet, x/tools/go/analysis)NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions