Skip to content

x/tools/go/analysis/passes/modernize: fmtappendf produces uncompilable code with multi-line []byte type cast #77821

@JoeLancaster

Description

@JoeLancaster

Go version

go version go1.26.0 linux/amd64

Output of go env in your module/workspace:

AR='ar'
CC='gcc'
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_ENABLED='1'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
CXX='g++'
GCCGO='gccgo'
GO111MODULE=''
GOAMD64='v1'
GOARCH='amd64'
GOAUTH='netrc'
GOBIN=''
GOCACHE='/home/joe/.cache/go-build'
GOCACHEPROG=''
GODEBUG=''
GOENV='/home/joe/.config/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFIPS140='off'
GOFLAGS=''
GOGCCFLAGS='-fPIC -m64 -pthread -Wl,--no-gc-sections -fmessage-length=0 -ffile-prefix-map=/tmp/go-build730289841=/tmp/go-build -gno-record-gcc-switches'
GOHOSTARCH='amd64'
GOHOSTOS='linux'
GOINSECURE=''
GOMOD='/home/joe/gofixbug/go.mod'
GOMODCACHE='/home/joe/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='linux'
GOPATH='/home/joe/go'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/usr/local/go'
GOSUMDB='sum.golang.org'
GOTELEMETRY='local'
GOTELEMETRYDIR='/home/joe/.config/go/telemetry'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/usr/local/go/pkg/tool/linux_amd64'
GOVCS=''
GOVERSION='go1.26.0'
GOWORK=''
PKG_CONFIG='pkg-config'

What did you do?

Run go fix on the example:

package t

import "fmt"

type T struct {
	S string
}

func (t *T) Bytes() []byte {
	return []byte(
		fmt.Sprintf("S=%s", t.S),
	)
}

What did you see happen?

The return statement is placed above the rewrite of fmt.Sprintf producing a naked return that will not compile:

package t

import "fmt"

type T struct {
	S string
}

func (t *T) Bytes() []byte {
	return
	fmt.Appendf(nil, "S=%s", t.S)
}
$> go build t.go
# command-line-arguments
./t.go:10:2: not enough return values
	have ()
	want ([]byte)
./t.go:12:1: missing return

What did you expect to see?

The rewrite should produce the return alongside the new fmt.Appendf call.

Compacting the []byte() cast to one line:

package t

import "fmt"

type T struct {
	S string
}

func (t *T) Bytes() []byte {
	return []byte(fmt.Sprintf("S=%s", t.S))
}

And running go fix produces compiling code:

package t

import "fmt"

type T struct {
	S string
}

func (t *T) Bytes() []byte {
	return fmt.Appendf(nil, "S=%s", t.S)
}

This output should also be produced for multi-line type casts.

Metadata

Metadata

Assignees

Labels

BugReportIssues describing a possible bug in the Go implementation.ToolsThis label describes issues relating to any tools in the x/tools repository.

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions