Go Fails to Infer Type in Assignment: Understanding the Issue
This question pertains to a type inference error encountered when assigning values to struct fields using the short declaration notation in Go.
The Issue
Consider the following code snippet:
i := 10 next := 11 prev, i := i, next
This code works as intended, inferring the correct types for prev and i. However, a seemingly similar snippet involving a struct field assignment fails to type infer:
type Foo struct { Bar int } f := Foo{10} next := 11 prev, f.Bar := f.Bar, next
This time, Go complains about a "non-name on left side of :=".
The Explanation
The difference lies in the fact that when assigning to a struct field using the short declaration syntax, Go expects the left-hand side to be the struct name followed by a dot (.) and the field name. For example, f.Bar. However, f alone is not a valid left-hand side for assignment.
The Solution
The proper way to assign to a struct field using the short declaration notation is:
f.Bar, prev = next, f.Bar
This syntax clearly indicates the struct name, field name, and assignment operation.
Is It a Bug?
The behavior discussed here is not a bug. It is a limitation of the short declaration notation. However, there is an open issue (Issue 6842) on the Go issue tracker that proposes extending the short declaration syntax to allow assigning to struct fields. Until this issue is resolved, it is recommended to use the more verbose alternative shown above.
The above is the detailed content of Why Does Go Fail to Infer Types When Assigning to Struct Fields Using Short Variable Declarations?. For more information, please follow other related articles on the PHP Chinese website!