Skip to content

unused: flag unused variables with initializers #507

@dominikh

Description

@dominikh

The rewrite of unused no longer flags the following code:

package pkg
var x = [3]int{1,2,3}

This is caused by the SSA that go/ssa produces:

func init():
0:                                                                entry P:0 S:2
	t0 = *init$guard                                                   bool
	if t0 goto 2 else 1
1:                                                           init.start P:1 S:1
	*init$guard = true:bool
	t1 = &x[0:int]                                                     *int
	t2 = &x[1:int]                                                     *int
	t3 = &x[2:int]                                                     *int
	*t1 = 1:int
	*t2 = 2:int
	*t3 = 3:int
	jump 2
2:                                                            init.done P:2 S:0
	return

Because the init function is taking addresses of values in x, x is clearly used.

This is not a problem for slices, because they generate different code (an array gets constructed, sliced, and assigned to the variable. Assignment alone isn't considered a use.)

This is, however, also a problem for structs, as

var x = t{1}

generates

t1 = &x.x [#0]                                                     *int
*t1 = 1:int

Another annoying side effect of this is that function calls used as part of the initialization are marked as used by the init function, not the variable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions