Value and Pointer Semantic when Passing Method to Variable

85 阅读1分钟

In this article, I want to explore the value and pointer semantic while passing method of struct to a variable and calling this method through variable.

package main

import (
	"fmt"
)

type user struct {
	email string
}

func (u user) displayEmail() {
	fmt.Println(u.email)
}

func (u *user) setEmail(email string) {
	u.email = email
}

func main() {
	u := user{
		email: "e1",
	}

	f1 := u.displayEmail
	f1()
	u.setEmail("e2")
	f1()

	f2 := u.setEmail
	f2("e2")
	u.displayEmail()
}

As you see above code, displayEmail has a value receiver, when assigning this method to a variable named f1, the underlying copy of u related with f1 does not change, setEmail has pointer receiver, so the f2("e2") calling modifies the u itself,

e1
e1
e2