Home >Backend Development >Golang >Why Does Go's Type Inference Fail for Struct Fields in Short Variable Declarations?
Consider the following Go code snippet:
i := 10 next := 11 prev, i := i, next
In this snippet, the type of i is successfully inferred as int during assignment. However, when a similar snippet involves a struct field, the type inference fails, as illustrated below:
type Foo struct { Bar int } f := Foo{10} next := 11 prev, f.Bar := f.Bar, next
In the latter snippet, the type inference for f.Bar fails with the error message "non-name f.Bar on left side of :=".
To explain this behavior, we turn to the relevant issue in the Go tracker:
Issue 6842 ("spec: Assigning to fields with short declaration notation") documents this behavior as an outstanding issue. The problem stems from the ambiguity in the syntax of the assignment. Specifically, the compiler cannot determine whether f.Bar is intended to be a variable name or a field name within the expression f.Bar, next.
While the issue report marks it as open, later comments suggest that it may have been resolved or superseded by other changes. However, the latest official word remains that this is a known issue.
The above is the detailed content of Why Does Go's Type Inference Fail for Struct Fields in Short Variable Declarations?. For more information, please follow other related articles on the PHP Chinese website!