Golang Receiver 和 函数参数的区别

我们来比较下面两种方式
https://grisha.org/blog/2016/09/22/golang-receiver-vs-function/

func (d *duck) quack() { // receiver
     // do something
}
func quack(d *duck) { // funciton argument
    // do something
}

如果我们习惯于对象的话,可能会觉得 d.quack() 更加直观,熟悉可读性也更好。但是并非真正原因,原因如下:

First, what is the essential difference? It is that at the time of the call, the receiver is an interface and the function to be called is determined dynamically. If you are not using interfaces, then this doesn’t matter whatsoever and the only benefit you are getting from using a method is syntactic sweetness.
最重要的本质是:receiver 和 interface 相关,函数可以被动态调用。如果你不使用innterface,那么无所谓使用哪个,唯一的优势是方法的语法糖。

But what if you need to write a test where you want to stub out quack(). If your code looks like this, then it is not possible, because methods are attached to their types inflexibly, you cannot change them, and there is no such thing as a “method variable”:

但是

猜你喜欢

转载自blog.csdn.net/weixin_44328662/article/details/86635834