./prog.go:26:15: syntax error: x := f used as value
./prog.go:27:2: syntax error: unexpected case, expecting expression
./prog.go:28:19: syntax error: unexpected ), expecting comma or }
The problem is that switch x := f{10}; makes the parser think that {10} is the ExprCaseClause (the body of the switch statement) because x := f is a valid expression.
This is what the parser sees:
switch x := f {
10
};
x := f can not be the expression because assignments and declarations don’t return a value, that’s why the first error comes up: syntax error: x := f used as value
You can change it to x := (f{10}) to make it work.
Btw it works with x := struct {a int}{10} because this can’t be falsely broken into x := struct or x := struct {a int} because those are invalid/incomplete expressions.
Thanks! Seems odd though that Go can interpret correctly with x := struct {a int}{10}, but gets confused with x := f{10}. As far as I can see, both are valid assignments (and x := f is an invalid assignment, just as x := struct {a int} is) and conform to the spec (https://golang.org/ref/spec#Switch_statements). Worth reporting as bug or am I missing something?