You can only assign to something which is addressable in the sense of https://golang.org/ref/spec#Address_operators.
That is: "either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array." You want "a field selector of an addressable struct operand", but the return value of a function is not addressable (it's not a variable, pointer, etc etc). By contrast, in the case where your function returns a pointer, then the struct is the result of a pointer indirection (so it's addressable) and the field selection is thus addressable too. Thomas On Wed, Nov 20, 2019 at 5:41 PM 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? > > TIA, > Orson > > > -- > 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/aaead2ec-b5b8-48d0-80e5-5275eeb583c2%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/aaead2ec-b5b8-48d0-80e5-5275eeb583c2%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- 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/CA%2BYjuxtP_WBOULA2VTb_-2QJn9YDYrX%2BWZpsZPzMndgsGy%3DaAQ%40mail.gmail.com.