On Tue, Aug 10, 2021 at 12:01 PM E Z <legend...@gmail.com> wrote:

> I feel confused when I use the function pointer which point to the struct
> method. Here is the test code:
>
> /***
> package main
>
> type Zoo struct {
>     Animal string
> }
>
> func (z Zoo) Display(){
>     fmt.Printf("Current animal is:%s\n", z.Animal)
> }
>

This method has a value receiver. When pf is assigned to gz.Display, it is
assigned with its receiver, which is a copy of gz.

Change the method to func (z *Zoo) Display(), and it will work as you
expect.


>
> func main(){
>     gz := &Zoo{
>         Animal: "Monkey",
>     }
>
>     pf := gz.Display
>     pf()                                       //display "Current animal
> is Monkey"
>     gz.Animal="Tiger"
>     pf()                                        //display "Current animal
> is Monkey"
>     gz.Display()                         //display "Current animal is
> Tiger"
> }
> ***/
> As the code is shown above,  even though I changed the value of the member
> field of the Zoo instance gz,  the function pointer call that followed
> still prints the unmodified value.
>
> Can someone help explain why? In my opinion, The function pointer pf
> should bind to the instance gz and its method(note that gz here is a
> pointer variable),  if so anytime I change the value of the variable gz,
> pf should reflect the changes.
>
> Thanks,
> Ethan
>
> --
> 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/60c6523c-dbce-4530-aa51-06f2c1223ca8n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/60c6523c-dbce-4530-aa51-06f2c1223ca8n%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/CAMV2RqoFhtb0Zs%3DOVBX-7X1CzXp4yf%2BpeCeR9N_efPQGo67u%3Dg%40mail.gmail.com.

Reply via email to