Reputation: 12376
How do you assign a struct field variable in a multiple assignment statement? Please refer to code below.
type TestMultipleReturns struct {
value string
}
func (t *TestMultipleReturns) TestSomething() {
someMap := make(map[string]string)
someMap["Test"] = "world"
t.value, exists := someMap["doesnotexist"] // fails
// works, but do I really need a 2nd line?
tmp, exists := someMap["doesnotexist"]
t.value = tmp
if exists == false {
fmt.Println("t.value is not set.")
} else {
fmt.Println(t.value)
}
}
Upvotes: 2
Views: 3651
Reputation:
Short variable declaration do not support assigning struct receiver properties; they are omitted from the spec definition:
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new.
The fix is to define exists
before the assignment and not use short variable declarations:
type TestMultipleReturns struct {
value string
}
func (t *TestMultipleReturns) TestSomething() {
someMap := make(map[string]string)
someMap["Test"] = "world"
var exists bool
t.value, exists = someMap["doesnotexist"]
if exists == false {
fmt.Println("t.value is not set.")
} else {
fmt.Println(t.value)
}
}
Upvotes: 6