You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I tried to compile the following program with the uncommented if-statement.
package main
import "fmt"
type S struct {
value int
}
func main() {
if x := (S{5}); x.value != 5 {
fmt.Printf("x\n")
}
// The following commented if-statement, if uncommented does not compile.
// Note that there are no parentheses around S{5} as in the above
// if-statement.
//if y := S{5}; y.value != 5 {
// fmt.Printf("y\n")
//}
// The compile error is:
// ./main.go:18:14: syntax error: y := S used as value
// ./main.go:28:1: syntax error: non-declaration statement outside function body
// In another program, with essentially the same if-statement, the compile
// error is:
// time_test.go:51:8: expected boolean expression, found assignment (missing parentheses around composite literal?)
}
What did you expect to see?
I would expect that the program with the uncommented if-statement also compiles.
What did you see instead?
A compile error (see code above).
The problem seems to be the assignment y := S{5} in the if-statement. When putting parentheses
around the struct, i.e., y := (S{5}), the program compiles. Is this a bug in the parser (precedence of := over S{5})?
The text was updated successfully, but these errors were encountered:
this is a known parsing ambiguity in the language grammar. From the Composite literals Section of the Specification:
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.
if x == (T{a,b,c}[i]) { … }
if (x == T{a,b,c}[i]) { … }
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes.
I have not tried earlier Go versions.
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
I tried to compile the following program with the uncommented if-statement.
What did you expect to see?
I would expect that the program with the uncommented if-statement also compiles.
What did you see instead?
A compile error (see code above).
The problem seems to be the assignment y := S{5} in the if-statement. When putting parentheses
around the struct, i.e., y := (S{5}), the program compiles. Is this a bug in the parser (precedence of := over S{5})?
The text was updated successfully, but these errors were encountered: