Go语言 函数类型实现接口——把函数作为接口来调用实例

  其他类型能够实现接口,函数也可以,本节将对结构体与函数实现接口的过程进行对比。

  完整的代码:

package main

import "fmt"

/*
这个接口需要实现 Call() 方法,调用时会传入一个 interface{} 类型的变量,这种类型的变量表示任意类型的值。
*/
type Invoker interface {
    //调用器接口
    Call(interface{})
}

/*
定义结构体,该例子中的结构体无须任何成员,主要展示实现 Invoker 的方法。
*/
type Struct struct {
}

/*
Call() 为结构体的方法,该方法的功能是打印 from struct 和传入的 interface{} 类型的值。
*/
func (s *Struct) Call(p interface{}) {
    fmt.Println("from struct", p)
}

//函数定义为类型
type FuncCaller func(interface{})

/*
将 func(v interface{}){} 匿名函数转换为 FuncCaller 类型(函数签名才能转换),此时 FuncCaller 类型实现了 Invoker 的 Call() 方法,赋值给 invoker 接口是成功的
*/
func (f FuncCaller) Call(p interface{}) {
    f(p)
}

func main() {
    //声明接口变量
    var invoker Invoker

    /*
        使用 new 将结构体实例化,此行也可以写为 s:=&Struct。
    */
    s := new(Struct)
    //将实例化的结构体赋值到接口
    invoker = s
    //使用接口调用实例化结构体方法
    invoker.Call("hello")
    //将匿名函数转为FuncCaller类型,再赋值给接口
    invoker = FuncCaller(func(v interface{}) {
        fmt.Println("from function", v)
    })
    //使用接口调用FuncCaller.Call,内部会调用 函数主体
    invoker.Call("hello")
}

  程序输出:

from struct hello
from function hello