Home > Backend Development > Golang > Why Does Go Fail to Infer Types When Assigning to Struct Fields Using Short Variable Declarations?

Why Does Go Fail to Infer Types When Assigning to Struct Fields Using Short Variable Declarations?

Susan Sarandon
Release: 2024-12-18 12:06:10
Original
790 people have browsed it

Why Does Go Fail to Infer Types When Assigning to Struct Fields Using Short Variable Declarations?

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
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template