Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go fails to infer type in assignment: "non-name on left side of :="

This snippet works as expected play.golang.org/p/VuCl-OKMav

i := 10
next := 11
prev, i := i, next

However this nearly identical snippet gives non-name f.Bar on left side of := play.golang.org/p/J8NNWPugQG

type Foo struct {
    Bar int
}

f := Foo{10}
next := 11
prev, f.Bar := f.Bar, next

What's special about the struct that stops type inference? Is this a bug?

like image 990
deft_code Avatar asked Jan 25 '14 01:01

deft_code


2 Answers

It's an open issue.

Issue 6842: spec: Assigning to fields with short declaration notation

like image 66
peterSO Avatar answered Oct 16 '22 08:10

peterSO


It's not really a type inference issue, it's just that the left-hand-side of := must be a list of identifiers, and f.Bar is not an identifier, so it can't be declared — not even with :='s slightly-more-permissive rules for what it can declare. See "Short variable declarations" in The Go Programming Language Specification.

like image 21
ruakh Avatar answered Oct 16 '22 08:10

ruakh