内容简介:我试验的返回对象的类型是空接口,然后用类型断言转换成含有一组约定方法的接口。我们首先在主程序中定义一个约定返回接口:
golang
的 plugin
功能用的比较少,官方的示例只有返回函数,而没有返回对象。但是实际应用中 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!")
结束
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- C++ 函数可以直接返回一个对象吗?
- c++ 为什么在返回从函数的返回类型派生的类型的本地对象时,没有选择move构造函数?
- C# 永远不会返回的方法真的不会返回
- iOS之导航返回上上个控制器或指定返回某个控制器
- MyBatis返回Map
- (译)从路由返回数据
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Sovereign Individual
James Dale Davidson、William Rees-Mogg / Free Press / 1999-08-26 / USD 16.00
Two renowned investment advisors and authors of the bestseller The Great Reckoning bring to light both currents of disaster and the potential for prosperity and renewal in the face of radical changes ......一起来看看 《The Sovereign Individual》 这本书的介绍吧!