转载于 https://zhuanlan.zhihu.com/p/34567697
有的时候我们需要 interface
type Formatter interface {
Format(space []byte, kv []interface{}) []byte
}
func doSomething(x Formatter) {...}
interface比较方便做组合
有的时候用 func 更方便,可以直接inline写实现
type Formatter func(space []byte, kv []interface{}) []byte
func doSomething(x Formatter) {...}
那有没有两全齐美的办法呢?有的,把函数转换成 interface 就可以了:
type FuncFormatter func(space []byte, kv []interface{}) []byte
func (f FuncFormatter) Format(space []byte, kv []interface{}) []byte {
return f(space, kv)
}
使用的时候需要有interface的可以传interface。有func的,用FuncFormatter()包一下,就变成interface了。
就是当你斟酌,我是应该拿一个interface作为参数类型,还是用一个函数指针作为参数类型的时候。不用再斟酌了。选择interface作为参数类型。因为所有的func,都可以很容易转换成interface。
网友评论