"Used as value" error with custom type

I’m getting a syntax error when using custom type to initialize switch (or for), pretty sure I’m missing something basic…could you help please?

package main

import (
	"fmt"
)

func main() {
	type f struct {a int}
	newF := func(a int) f {
		return f{a}
	}
	
	// Works
	switch x := newF(10); x.a {
	case 10:
		fmt.Println("OK")
	}
	
	// Works
	switch x := struct {a int}{10}; x.a {
	case 10:
		fmt.Println("OK")
	}
	
	// Syntax error
	switch x := f{10}; x.a {
	case 10:
		fmt.Println("OK")
	}
}

This is a really good question.

switch x := f{10}; x.a {
case 10:
	fmt.Println("OK")
}

The error message is: (see Go Playground)

./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?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.