zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    vim常用命令
    Leetcode686.Repeated String Match重复叠加字符串匹配
    Leetcode686.Repeated String Match重复叠加字符串匹配
    (转)Sql server中 如何用sql语句创建视图
    (转)Sql server中 如何用sql语句创建视图
    SQL Sever实验三 视图与数据更新
    SQL Sever实验三 视图与数据更新
    Leetcode653.Two Sum IV
    Leetcode653.Two Sum IV
    Leetcode661.Image Smoother图片平滑器
  • 原文地址:https://www.cnblogs.com/personblog/p/12319024.html
Copyright © 2011-2022 走看看