Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't use composite literal in for clause #43916

Closed
Storyyeller opened this issue Jan 26, 2021 · 2 comments
Closed

Can't use composite literal in for clause #43916

Storyyeller opened this issue Jan 26, 2021 · 2 comments

Comments

@Storyyeller
Copy link

Storyyeller commented Jan 26, 2021

What version of Go are you using (go version)?

Whatever is on the Go Playground.

Does this issue reproduce with the latest release?

Assuming Go Playground is up to date, yes.

What operating system and processor architecture are you using (go env)?

N/A

What did you do?

Playground link: https://play.golang.org/p/yYCbpnPJdlL

I get a strange syntax error when attempting to use a composite literal inside a for loop, even though as far as I can tell from the specification, this is valid syntax.

package main

import (
	"fmt"
)

type Test struct{}

func main() {
	for i := Test{};; {
		fmt.Println("Hello, playground", i)
		break
	}
}

What did you expect to see?

No syntax errors

What did you see instead?

./prog.go:10:8: syntax error: cannot use i := Test as value

@randall77
Copy link
Contributor

This is a known limitation of the parser.

See https://golang.org/ref/spec#Composite_literals ,

A parsing ambiguity arises when a composite literal using the TypeName form of the LiteralType appears as an operand between the keyword and the opening brace of the block of an "if", "for", or "switch" statement, and the composite literal is not enclosed in parentheses, square brackets, or curly braces. In this rare case, the opening brace of the literal is erroneously parsed as the one introducing the block of statements. To resolve the ambiguity, the composite literal must appear within parentheses.

@Storyyeller
Copy link
Author

Thanks!

@golang golang locked and limited conversation to collaborators Jan 26, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants