#81576·Go

x/tools/gopls: slicesbackward modernizer produces non-compiling code for a backward loop with an empty body

Author: 0xff-devCreated Sep 17, 2026Updated Sep 17, 2026
LabelsgoplsTools

Go version

go version go1.27.1 darwin/amd64

Output of go env in your module/workspace:

AR='ar'
CC='clang'
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_ENABLED='1'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
CXX='clang++'
GCCGO='gccgo'
GO111MODULE=''
GOAMD64='v1'
GOARCH='amd64'
GOAUTH='netrc'
GOBIN='/Users/shuang/.go/bin'
GOCACHE='/Users/shuang/Library/Caches/go-build'
GOCACHEPROG=''
GODEBUG=''
GOENV='/Users/shuang/Library/Application Support/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFIPS140='off'
GOFLAGS=''
GOGCCFLAGS='-fPIC -arch x86_64 -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/lr/dqj7nfq51jvffgb4ghtclg080000gn/T/go-build1269350979=/tmp/go-build -gno-record-gcc-switches -fno-common'
GOHOSTARCH='amd64'
GOHOSTOS='darwin'
GOMOD='/dev/null'
GOMODCACHE='/Users/shuang/.go/pkg/mod'
GOOS='darwin'
GOPACKAGESDRIVER=''
GOPATH='/Users/shuang/.go'
GOPROXY='https://goproxy.cn,direct'
GOROOT='/usr/local/go'
GOSUMDB='sum.golang.org'
GOTELEMETRY='off'
GOTELEMETRYDIR='/Users/shuang/Library/Application Support/go/telemetry'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/usr/local/go/pkg/tool/darwin_amd64'
GOVCS=''
GOVERSION='go1.27.1'
GOWORK=''
PKG_CONFIG='pkg-config'

What did you do?

The slicesbackward modernizer (go/analysis/passes/modernize) offers a fix on a backward loop whose body makes no use of the index, e.g. an empty body:

package main

func empty(s []int) {
        for i := len(s) - 1; i >= 0; i-- {

        }
}

func main() {
        empty(nil)
}

go run is ok.

What did you see happen?

The suggested fix rewrites the loop to

package main

import "slices"

func empty(s []int) {
        for _, v := range slices.Backward(s) {

        }
}

func main() {
        empty(nil)
}
# command-line-arguments
./b.go:6:9: declared and not used: v

What did you expect to see?

Either no fix offered, or a fix that produces compilable code.