Skip to content

cmd/gofmt: inconsistent behavior on removing unnecessary type names with -s arg #64966

@fishy

Description

@fishy

Go version

go version go1.21.5 linux/amd64

Output of go env in your module/workspace:

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

What did you do?

main.go:

package main

import (
	"fmt"
)

type Data struct {
	Foo int
}

type Response struct {
	Item  []*Data
	Items [][]*Data
}

var s = Response{
	Item: []*Data{
		&Data{
			Foo: 1,
		},
	},
	Items: [][]*Data{
		{
			&Data{
				Foo: 2,
			},
			&Data{
				Foo: 3,
			},
		},
	},
}

func main() {
	fmt.Println(s)
}

gofmt -s -d main.go will only suggest removing &Data from Item, but not from Items:

$ gofmt -s -d main.go
diff main.go.orig main.go
--- main.go.orig
+++ main.go
@@ -15,7 +15,7 @@
 
 var s = Response{
        Item: []*Data{
-               &Data{
+               {
                        Foo: 1,
                },
        },

But removing both are perfectly fine: https://go.dev/play/p/pEfXLBwuwL1

What did you see happen?

gofmt -s is inconsistent as it fail to suggest the same thing when it's under two or more layers of slices.

What did you expect to see?

gofmt -s being consistent.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixPendingIssues that have a fix which has not yet been reviewed or submitted.NeedsFixThe path to resolution is known, but the work has not been done.SuggestedIssues that may be good for new contributors looking for work to do.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions