gordonklaus / ineffassign

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

Why is this not reported ? #70

Closed eddycharly closed 2 years ago

eddycharly commented 2 years ago

Let's consider the code below:

package main

import "fmt"

type inner struct {
    s string
}

type outer struct {
    inner []inner
}

func main() {
    o := outer{
        inner: []inner{{
            s: "a",
        }},
    }
    for _, i := range o.inner {
        i.s = "b"
    }
    fmt.Println(o)
}

Shouldn't this code be reported ? i.s = "b" will have no effect here.

eddycharly commented 2 years ago

For example, assignments to struct fields are never marked as ineffectual.

Because of this maybe ?

gordonklaus commented 2 years ago

Yes, basically. Assignments to struct fields and array elements are not checked.

I suppose it might not be too much work to check whether a struct/array is ever used (or escapes) after having a field/element assigned to. But I don't plan to do it :)

eddycharly commented 2 years ago

Thanks for clearing it up ! Do you know a tool that could report the code above as potentially wrong ? (useless assignment, useless code, or any kind of warning that could help drawing a developer attention ?)

This looks obvious that this code is wrong but I fail to find a tool that detects this simple code smell :(

gordonklaus commented 2 years ago

Maybe staticcheck?

eddycharly commented 2 years ago

staticcheck didn't report anything :( Feel free to close the issue.