go语言plugin怎么返回对象

栏目: Go · 发布时间: 6年前

内容简介:我试验的返回对象的类型是空接口,然后用类型断言转换成含有一组约定方法的接口。我们首先在主程序中定义一个约定返回接口:

golangplugin 功能用的比较少,官方的示例只有返回函数,而没有返回对象。但是实际应用中 OOP 可以极大提高程序的质量,经过我自己试验,发现 plugin 是可以返回对象的。

返回类型

我试验的返回对象的类型是空接口,然后用类型断言转换成含有一组约定方法的接口。

实例

我们首先在主程序中定义一个约定返回接口:

type ResObj interface {
    Say(string) int
}

插件中的对象定义和返回接口的函数:

//对象定义
type ObjType struct {
  //内部封装数据
    Name string
}
//Say 方法的实现
func (p *ObjType) Say(s string) int {
    fmt.Printf("%s say: %s\n", p.Name, s)
    return len(s)
}
//返回函数
func New(arg string) interface{}{
    return &ObjType{Name:arg}
}

在主程序中调用 plugin

p, err := plugin.Open(pluginPathName)
    if err != nil {
        panic(err)
    }
    f, err := p.Lookup("New")
    if err != nil {
        panic(err)
    }
    fn, ok := f.(func(string) interface{})
    if ok == false {
        panic("func type error: New.")
    }
    //New 返回空接口
    obj0 := fn("Fisher")
    //把空接口转换成`ResObj`接口
    obj1, ok := obj0.(ResObj)
    if ok == false {
        panic("Type error: ResObj.")
    }
    //调用接口的方法
    obj1.Say("Hello friend!")

结束


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Python Data Structures and Algorithms

Python Data Structures and Algorithms

Benjamin Baka / Packt Publishing / 2017-5-30 / USD 44.99

Key Features A step by step guide, which will provide you with a thorough discussion on the analysis and design of fundamental Python data structures.Get a better understanding of advanced Python c......一起来看看 《Python Data Structures and Algorithms》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器