On Wed, Nov 20, 2019 at 9:41 AM Orson Cart <objectivedynam...@gmail.com> wrote:
>
> I'm a newbie to Go having used C and C++ in the past and I'm puzzled about 
> something I've just seen.
>
> In the following code getEmployee returns a pointer to a struct. The return 
> value is then dereferenced. This code compiles and runs fine:
>
> package main
>
> type employee struct {
> ID   int
> name string
> }
>
> var dilbert employee
>
> func main() {
>
> getEmployee().name = "dilbert"
> }
>
> func getEmployee() *employee {
> return &dilbert
> }
>
> However if I modify getEmployee as follows, I get a compilation error:
>
> func getEmployee() employee {
> return dilbert
> }
>
> The error is: cannot assign to getEmployee().name
>
> I assume that it revolves around "assignability" but I'm struggling to 
> understand why.
>
> Can anyone tell me why this is?

There are two kinds of answers.

One is that the spec only permits setting fields of a struct that is
addressable, and the result of a function call is not addressable.
See https://golang.org/ref/spec#Assignments and
https://golang.org/ref/spec#Address_operators .

The other kind of answer is that if a function returns a pointer to a
struct, a value of type *employee, then it's normal for that something
else to have a copy of that pointer, perhaps some data structure or
global variable.  In your simple example that is the global variable
"dilbert".  So it makes sense to permit setting a field of the result
of calling getEmployee(), a value of type *employee, as setting that
field will change the global variable "dilbert".  But when
getEmployee() does not return a pointer, but just returns a value of
type "employee", then that is a copy of the value in the global
variable.  Changing a field in that copy won't change anything.  The
assignment will be made, and then the result will be discarded.  Since
that operation is useless, the language does not permit it.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcVz5oaDa98bXMKS5mKW-ya55dewcrUtmQZcy-v0-YUicg%40mail.gmail.com.

Reply via email to