Type Inference in Assignment with Structs
Type inference in Go is a convenient feature that allows you to omit explicit type annotations in certain scenarios. However, when assigning values to fields of structured types, certain limitations can arise.
Consider the following code snippets:
i := 10 next := 11 prev, i := i, next
Here, the assignment to i infers the type of prev and declares it as int.
type Foo struct { Bar int } f := Foo{10} next := 11 prev, f.Bar := f.Bar, next
In this code, however, the assignment to f.Bar fails to infer the type of prev. Instead, it produces the error: "non-name on left side of :=".
Why does this occur? It turns out that the presence of the struct type (Foo) disrupts the type inference process. In simple assignments (like the first code snippet), type inference relies on the context to determine the type of the assigned variable. However, in the second code snippet, the presence of the struct creates an expression with multiple components, making type inference ambiguous.
Is this a bug in Go? As it turns out, it is a known issue that has been discussed in Issue 6842:
Issue 6842: spec: Assigning to fields with short declaration notation
The issue remains unresolved, indicating that this behavior is intended. To work around this limitation, you can either explicitly type annotate the prev variable or use a longer form of assignment, such as f.Bar = next.
The above is the detailed content of Why Does Go's Type Inference Fail with Struct Field Assignments?. For more information, please follow other related articles on the PHP Chinese website!