美文网首页
[转载]把 Go 的函数转换成 interface

[转载]把 Go 的函数转换成 interface

作者: gensmusic | 来源:发表于2018-08-25 10:30 被阅读0次

转载于 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。

相关文章

网友评论

      本文标题:[转载]把 Go 的函数转换成 interface

      本文链接:https://www.haomeiwen.com/subject/ggiwiftx.html