13-2. go 接口型函数

1 什么是接口型函数?

某一函数类型实现了接口,该函数类型调用接口实现方法时再调用该函数类型本体,这种函数叫做接口型函数。

  • 示例代码

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    
    // 调用器接口
    type Invoker interface {
    	Call(interface{}) error
    }
    
    // 定义函数为类型
    type FuncCaller func(interface{}) error
    
    // 接口实现
    func (f FuncCaller) Call(i interface{}) error {
    	return f(i)  // 调用函数f本体
    }

2 优点

  1. 可以完美使用接口优点,不必将某个接口函数附在某个type上面
  2. 可以直接调用函数或者使用该接口,非常灵活
  • code demo

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    
    // interface_func project main.go 接口型函数基本使用
    package main
    
    import "fmt"
    
    type Handler interface {
        Do(k, v interface{})
    }
    
    type HandlerFunc func(k, v interface{})
    
    func (f HandlerFunc) Do(k, v interface{}) {
        f(k, v)
    }
    
    func Each(m map[interface{}]interface{}, h Handler) {
        if m != nil && len(m) > 0 {
            for k, v := range m {
                h.Do(k, v)
            }
        }
    }
    
    func SelfInfo(k, v interface{}) {
        fmt.Printf("我是%s,今年%d岁了\n", k, v)
    }
    
    func EachFunc(m map[interface{}]interface{}, f func(k, v interface{})) {
        Each(m, HandlerFunc(f))
    }
    
    func main() {
        SelfInfo("chaozhou", 23) //单独调用
        SelfInfo("lisi", 24)     //单独调用
        person := make(map[interface{}]interface{})
        person["chaozhou"] = 23
        person["lisi"] = 24
        EachFunc(person, SelfInfo) //函数接口参数调用
    }

3 应用场景

  • net/http 库中handlerhandlerFunc

相关内容

Buy me a coffee~
Fred 支付宝支付宝
Fred 微信微信
0%