gordonklaus / ineffassign

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

Initialization as nil treated as assignment #65

Closed leighmcculloch closed 2 years ago

leighmcculloch commented 2 years ago

Problem

It appears that ineffassign treats the assign of a nil value that is later replaced without being used a ineffectual assignment, however this is inconsistent with other types, such as bools, and ints, where a default value is allowed.

This issue shows up frequently when defining a pointer variable that will be nil, but then in a block, say inside a for loop or an if, the value will be set.

This errors forces rewriting s := (*S)(nil) to var s *S, which is style only.

Example in the wild

https://github.com/stellar/experimental-payment-channels/pull/204/files/07e7063a43892bd267575c7d6ae9c248424246c0#diff-6922f95bf6260135bad02efc30e1312aed8a596b33fa4871e3d64ccb27ceb73dR897

Reduced example

When I run ineffassign, using golangci-lint, I see this error for the following code:

test.go:8:2: ineffectual assignment to s (ineffassign)
        s := (*S)(nil)
        ^
package main

import "fmt"

type S struct{}

func main() {
    s := (*S)(nil)
    s = &S{}
    fmt.Println(s)
}

Thanks for making ineffassign! It has helped catch plenty of my silly mistakes before anyone else got to see them.

gordonklaus commented 2 years ago

Fixed, thanks!

leighmcculloch commented 2 years ago

Thanks!!!