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

Custom type braces in if statement #36645

Closed
guiguan opened this issue Jan 20, 2020 · 2 comments
Closed

Custom type braces in if statement #36645

guiguan opened this issue Jan 20, 2020 · 2 comments

Comments

@guiguan
Copy link

guiguan commented Jan 20, 2020

This will lead to a compilation error (expected ';', found '{'):

type Hash [32]byte

func main() {
  a := Hash{}
  if a == Hash{} {
  }
}

The workaround is to surround it with parentheses:

type Hash [32]byte

func main() {
  a := Hash{}
  if a == (Hash{}) {
  }
}

However, the primitive type works fine without parentheses:

type Hash [32]byte

func main() {
  a := Hash{}
  if a == [32]byte{} {
  }
}

Is this a parsing bug or expected behavior?

@kortschak
Copy link
Contributor

This is expected behaviour;

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.

@guiguan
Copy link
Author

guiguan commented Jan 20, 2020

@kortschak okay, thank you

@guiguan guiguan closed this as completed Jan 20, 2020
@golang golang locked and limited conversation to collaborators Jan 19, 2021
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