Skip to content

staticcheck: SA4006 false-negative when nil value used #733

@leighmcculloch

Description

@leighmcculloch
staticcheck -version
$ staticcheck -version
staticcheck 2020.1.3
staticcheck -debug.version
$ staticcheck -debug.version
staticcheck 2020.1.3

Compiled with Go version: go1.14.2
Main module:
        honnef.co/go/tools@v0.0.1-2020.1.3 (sum: h1:sXmLre5bzIR6ypkjXCDI3jHPssRhc8KD/Ome589sc3U=)
Dependencies:
        github.com/BurntSushi/toml@v0.3.1 (sum: h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=)
        golang.org/x/tools@v0.0.0-20191130070609-6e064ea0cf2d (sum: h1:/iIZNFGxc/a7C3yWjGcnboV+Tkc7mxr+p6fDztwoxuM=)
go version
$ go version
go version go1.14.2 linux/amd64
go env
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN="/home/leighmcculloch/local/bin"
GOCACHE="/home/leighmcculloch/.cache/go-build"
GOENV="/home/leighmcculloch/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/leighmcculloch/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/home/leighmcculloch/local/bin/go/1.14.2"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/home/leighmcculloch/local/bin/go/1.14.2/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/home/leighmcculloch/devel/stellar--go/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build002621866=/tmp/go-build -gno-record-gcc-switches"

Staticcheck is detecting an explicit nil value given to a variable as a value that isn't used.

See this simple example, that is a simpler version of the code I experienced this in:

package main

import "fmt"

func main() {
    slice := []string(nil)
    if true {
        slice = []string{"1", "2"}
    } else {
        slice = []string{"3", "4"}
    }
    fmt.Println(slice)
}
$ staticcheck
main.go:6:2: this value of slice is never used (SA4006)

If I change the code to not provide the nil value explicitly, staticcheck passes. I believe this is a false positive because there's no value to use, and there's no reason to prefer one syntax over the other. In both cases the same value has been set on the variable and in both cases the nil value does not need to be more used than the other to be correct code.

package main

import "fmt"

func main() {
    var slice []string
    if true {
        slice = []string{"1", "2"}
    } else {
        slice = []string{"3", "4"}
    }
    fmt.Println(slice)
}
$ staticcheck

The original error I experienced can be viewed in this CircleCI build and required this work-around to avoid the false positive.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions