Go语言实践技巧(7)——value receiver和pointer receiver

Value receiver:

func (u user) fun1() {
    ....
}

Pointer receiver:

func (u *user) fun2() {
    ....
}

Value receiver操作的是值的拷贝,而pointer receiver操作的是实际的值。

pointer去调用value receiver的方法,实际的操作是:

(*p).fun1()

而用value去调用pointer receiver的方法,实际的操作是:

(&v).fun2()

参考资料:
Go in Action

发表评论

邮箱地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.