gordonklaus / ineffassign

Detect ineffectual assignments in Go code.
MIT License
390 stars 22 forks source link

False Positive question #50

Closed glaslos closed 3 years ago

glaslos commented 3 years ago

I have a case where I want to nil a receiver under a certain condition. Let's say to nil/remove the age from a user which I fetched from the database:

type AgeType int

func (a *AgeType) UnmarshalJSON(data []byte) error {
    if len(data) == 0 {
        a = nil
        return nil
    }
    return nil
}

ineffassign would identify the a = nil.

gordonklaus commented 3 years ago

Assigning nil to a has no effect because a (just like any other function parameter) is local to the method. To be clear, what a points to may be accessible from elsewhere (in particular, the caller of this method), but this pointer itself is not.

To achieve what you want (removing a user's age), you'll have to somehow encode "nullability" in AgeType. You could do that by making it a struct with a valid bool field (in addition to age int) or with only an age *int field, or by treating negative ages as null (in which case your a = nil would become *a = -1.