Error struct assignment in if clause (language spec question)

19 Views Asked by At

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.

0

There are 0 best solutions below