D 的个人博客

但行好事莫问前程

  menu
417 文章
3446695 浏览
18 当前访客
ღゝ◡╹)ノ❤️

Go 边看边练 -《Go 学习笔记》系列(十一)

上一篇: [1438699210452]


ToC


5.4 表达式

根据调用者不同,方法分为两种表现形式:

1instance.method(args...) ---> <type>.func(instance, args...)

前者称为 method value,后者 method expression

两者都可像普通函数那样赋值和传参,区别在于 method value 绑定实例,而 method expression 则须显式传参。

需要注意,method value 会复制 receiver

在汇编层面,method value 和闭包的实现方式相同,实际返回 FuncVal 类型对象。

1FuncVal { method_address, receiver_copy }

可依据方法集转换 method expression,注意 receiver 类型的差异。

将方法 "还原" 成函数,就容易理解下面的代码了。

 1type Data struct{}
 2
 3func (Data) TestValue() {}
 4func (*Data) TestPointer() {}
 5
 6func main() {
 7	var p *Data = nil
 8	p.TestPointer()
 9	
10    (*Data)(nil).TestPointer() // method value
11	(*Data).TestPointer(nil) // method expression
12	
13    // p.TestValue() // invalid memory address or nil pointer dereference
14	// (Data)(nil).TestValue() // cannot convert nil to type Data
15	// Data.TestValue(nil) // cannot use nil as type Data in function argument
16}

下一篇: [1438845728987]



社区小贴士

  • 关注标签 [golang] 可以方便查看 Go 相关帖子
  • 关注标签 [Go 学习笔记] 可以方便查看本系列
  • 关注作者后如有新帖将会收到通知

该文章同步自 黑客派