'My function returns a struct; why is assignment to a field of that result value disallowed by the compiler?

In golang, if I return a struct type in a function, I got compilation error, I have to use the pointer of struct as the return type to achieve member access directly via the function call. Why is that? Doesn't foo() return a temporary variable of type Employee?

package main


type Employee struct {
ID int
Name string
Address string
Position string
Salary int
ManagerID int
}
var dilbert Employee


func foo() Employee {
    employee := Employee{}
    return employee
}

func bar() *Employee {
    employee := Employee{}
    return &employee
}

func main() {
    dilbert.Salary = 1
    var b = foo()
    b.Salary = 1

    bar().Salary = 1    // this is good
    foo().Salary = 1    // this line has the compilation error cannot assign to foo().Salary
}


Solution 1:[1]

foo() returns a 'value' of struct type and we can not assign anything to a value. While bar() returns a pointer to a variable. We can use this pointer to assign a different value to this variable

This error isn't essentially related to struct but with assigning value to a value. Consider the following example:


func retint() int{
    var a int=5
    return a
}

func retintp() *int{
    var a int=5
    return &a
}
func main(){
    print("hello")
    *retintp()=10   // this is valid as we can store 10 to address pointed by a
    retint()=10     // this gives error. as we can not assign 10 to 5

}

Here retint() returns a value (5). we can not assign anything to 5 but retintp() returns address of variable a. We can use this address to assign a value to it

Solution 2:[2]

bar().Salary = 1 

Returns a pointer and we are writing to the object pointed to by the pointer

foo().Salary = 1

foo() returns a temporary object, and since we are not storing it anywhere, the temporary object would be lost if not assigned to a variable. Hence go compiler is complaining

Following will work

f = foo()
f.Salary = 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 pr-pal