1

I get an error which I can't explain. Can you help me?

package main

import "fmt"

type mystruct struct {
    a string
}

func main() {

    // ok
    m := mystruct{"a"}
    if m.a == "x" {
        fmt.Println("is x")
    }

    // not ok, error is:
    // ./main.go:20:7: syntax error: cannot use b := mystruct as value
    // ./main.go:23:1: syntax error: non-declaration statement outside function body
    if b := mystruct{"x"} ; b.a == "aaa" {
        fmt.Println("is aaa")
    }
}

From the language spec:

The expression may be preceded by a simple statement, which executes before the expression is evaluated.

if x := f(); x < y {
    return x
} else if x > z {
    return z
} else {
    return y
}

The simple statement can be an assignment (among other things) but I cannot find why b := mystruct{"x"} is not an assignment or where the problem is.

topskip
  • 16,207
  • 15
  • 67
  • 99
  • 3
    `if b := (mystruct{"x"}) ; b.a == "aaa" {` The first `{` is confusing the parser of the `if` statement, it thinks that's the start of the if's body, you need to use the parentheses to help guide it. – mkopriva Sep 07 '22 at 07:22
  • 1
    @mkopriva OK that makes sense. Thank you very much. If you turn it into an answer, I'll happily upvote it and mark it as an answer. – topskip Sep 07 '22 at 07:25

0 Answers0