【发布时间】:2014-05-19 05:45:32
【问题描述】:
我最近了解到,在 net/http 包中,有一种使用模式最让我感到困惑。是函数类型转换。是这样的:
(function a) ->convert to-> (type t)
(type t) ->implentments-> (interface i)
所以,如果有一个函数以接口i为参数,它会调用函数a,这就是net/http的实现方式。
但是当我编写自己的代码时,我对这种模式有很多误解。我的代码是这样的:
package main
import (
"fmt"
)
type eat interface {
eat()
}
type aaa func()
func (op *aaa) eat() {//pointer receiver not right
fmt.Println("dog eat feels good")
}
///////////////////////////////////////////////
func dog() {
fmt.Println("I'm a dog")
}
///////////////////////////////////////////////
func feelsGood(a eat) {
a.eat()
}
func main() {
b := aaa(dog)
feelsGood(b)
}
//error:aaa does not implement eat (eat method has pointer receiver)
类型aaa有方法eat,函数名和参数签名相同,符合接口eat的规则,但是为什么会报这个错误呢?接收者重要吗?
另外一个问题是只有函数和类型,不包括接口,代码如下:
package main
import (
"fmt"
)
type aaa func()
func (op *aaa) eat() {
op()
}
///////////////////////////////////////////////
func dog() {
fmt.Println("I'm a dog")
}
///////////////////////////////////////////////
func main() {
obj:=aaa(dog)
obj.eat()
}
//error:cannot call non-function op (type *aaa)
首先,op 是匿名函数,不管错误如何?
其次,我去掉星号后效果很好,但为什么呢? op 是 aaa 类型的实例,接收者是 op,op 是否代表函数 dog()? http包同样使用f(w,r),但是理解起来有点难。 op 是类型、实例还是匿名函数?
看来我对函数转换的理解是不对的,不过我也查了很多谷歌的帖子,都没有教我怎么去思考和正确使用。谢谢!
【问题讨论】:
标签: function types go type-conversion