2

Please excuse me for not knowing the proper name for the following syntax

type Foo struct{}
func (Foo) One() (int, error) {
     // Logic...
}

func (Foo) Two() (int, error) {
    // Logic
}

I am using the empty struct Foo as a way to group some of the similar functions. So when I call the function One, I will use the following syntax:

fooNum, err := Foo{}.One()

It works perfectly fine until I try to do the following:

if fooNum, err := Foo{}.One(); err == nil {
    // Logic...
}

I get syntax error: unexpected newline, expecting comma or }. I wonder why is this the case? Is there a bigger reason behind this error? Am I doing something that is discouraged by general Go style?

mofury
  • 644
  • 1
  • 11
  • 23
  • 4
    The braces `{}` in `Foo{}` you intend to be part of the struct literal cause a parsing ambiguity, as the compiler can't tell if they're part of the struct literal or they form the body of the `if` statement. You have to parenthesize it: `if fooNum, err := (Foo{}).One(); err == nil { ... }` – icza Apr 13 '18 at 18:59
  • You may want to simplify your syntax a bit: https://play.golang.org/p/ZXn7YMjr1bu. Alternatively, if you're not causing import cycles, just make a package called foo. – Peter Apr 13 '18 at 19:05
  • As a sidenote: If you do not need the struct, you could define the `func` on package level. If you had the package `foo`, then the call would be `foo.One()` and `foo.Two()`. – mbuechmann Apr 13 '18 at 19:51

0 Answers0