Skip to content

cmd/compile: unable to use composite literal directly as part of range expression #69017

@nan0tube

Description

@nan0tube

Go version

go version go1.23.0 linux/amd64

Output of go env in your module/workspace:

GO111MODULE=''
GOARCH='amd64'
GOBIN=''
GOCACHE='/home/user/.cache/go-build'
GOENV='/home/user/.config/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='amd64'
GOHOSTOS='linux'
GOINSECURE=''
GOMODCACHE='/home/user/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='linux'
GOPATH='/home/user/go'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/usr/local/go'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/usr/local/go/pkg/tool/linux_amd64'
GOVCS=''
GOVERSION='go1.23.0'
GODEBUG=''
GOTELEMETRY='local'
GOTELEMETRYDIR='/home/user/.config/go/telemetry'
GCCGO='gccgo'
GOAMD64='v1'
AR='ar'
CC='gcc'
CXX='g++'
CGO_ENABLED='1'
GOMOD='/home/user/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-build2151432987=/tmp/go-build -gno-record-gcc-switches'

What did you do?

package main

import "fmt"

type S struct {
	Slice []int
}

func main() {
	// Works.
	s := S{}
	for _, v := range s.Slice {
		fmt.Print(v)
	}

	// Error: syntax error: unexpected . at end of statement
	for _, v := range S{}.Slice {
		fmt.Print(v)
	}
}

https://go.dev/play/p/t_G0ZOb51EG

The statement for _, v := range S{}.Slice {} throws a syntax error due to the direct use of composite literal S{} as part of the range expression.

Will be good to see composite literal being supported directly inside range expression, especially with the introduction of range-over-func (e.g. range interval{a, b}.Step()).

As a workaround, the statement for _, v := range (S{}).Slice {} works but appears unintuitive, when expression S{}.Slice can be trivially used in most other statements.

What did you see happen?

syntax error: unexpected . at end of statement on the line where the composite literal is used as part of the range expression.

What did you expect to see?

No syntax error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions