Skip to content

cmd/compile: struct initialization in "if" doesn't compile #38036

Closed

Description

@menghanl

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

$ go version
go version go1.14.1 linux/amd64

Does this issue reproduce with the latest release?

Yes

What did you do?

https://play.golang.org/p/TACak6vfX1a

package main

import (
	"fmt"
)

type foo struct{}

func main() {
	u := foo{}

	if (u != foo{}) { // With () it works
		fmt.Println("OK")
	}
	
	if u != foo{} { // This doesn't compile
		fmt.Println("hello")
	}
}

What did you expect to see?

No compile error

What did you see instead?

if u != foo{} { does not compile:

./main.go:16:16: syntax error: unexpected { at end of statement
./main.go:19:1: syntax error: non-declaration statement outside function body

Adding parentheses works:

  • if (u != foo{}) {
  • if u != (foo{}) {

Activity

  1. changed the title [-]cmd/compile: struct initialization in if doesn't compile[/-] [+]cmd/compile: struct initialization in "if" doesn't compile[/+] on Mar 23, 2020
  2. ianlancetaylor commented on Mar 23, 2020

    @ianlancetaylor
    Contributor

    This is expected and documented. Search for "ambiguity" in https://golang.org/ref/spec#Composite_literals.

  3. locked and limited conversation to collaborators on Mar 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions