这篇文章将为大家详细讲解有关如何在Golang中利用接口实现泛型,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
实现一个最简单的vector,并实现插入时排序的功能。
type Comper interface{
Lessthan (Comper) bool
}
type Sdata struct{
data []Comper
}
func (t *Sdata) Push (item Comper){
t.data = append(t.data, item)
for k,v:=range t.data{
if item.Lessthan(v) { //调用接口定义的方法
//排序操作
break
}
}
}
如此便实现了一个最简单的Demo,使用Sdata的数组元素必须先实现Lessthan方法:
type Myint int
func (t Myint) Lessthan (x Comper) bool {
return t<x.(Myint)
}
func main() {
mydata := Sdata{make([]Comper, 0)}
for i:=10;i>0;i--{
mydata.Push((Myint(i)))
}
fmt.Println(mydata)
}
但这个Demo的缺点也有许多,一是简单类型元素无法使用Sdata进行排序,二是不支持并发,在并发的情况下会产生不可预料的结果。
通过Reflect支持简单类型的Demo
为要支持简单类型,我们只能使用空接口作为数组元素类型。这时候我们的程序逻辑应该是这样:如果这是一个简单类型,那么我们直接调用内置的"<"与">"进行比较;如果这不是一个简单类型,那么我们仍旧调用Lessthan方法:
type Comper interface{
Lessthan (Comper) bool
}
type Sdata struct{
data []interface{}
}
func (t *Sdata) Push (item interface{}){
for _,v:=range t.data{
if reflect.TypeOf(item).Implements(reflect.TypeOf(new(Comper)).Elem()) {
citem:=item.(Comper)
cv:=v.(Comper)
if citem.Lessthan(cv) {
//要执行的操作
break
}
}else{
x,v:=reflect.ValueOf(item),reflect.ValueOf(v)
switch x.Kind() {
case reflect.Int:
case reflect.Int8:
case reflect.Int16:
/*...*/
//x, y:=x.Int(), y.Int()
/*...*/
break
case reflect.Uint:
/*...*/
}
}
}
}
利用reflect判断item的类型:
reflect.TypeOf(item).Implements(reflect.TypeOf(new(comper)).Elem()),即item类型是否实现了comper接口类型。TypeOf(new(comper))是一个指针ptr,Elem()将指针转为值。如果该函数返回值为true,则可将item和v从interface{}强制转为Comper接口,调用Lessthan(...);当然你也可以使用类型断言,那种方式更简单也更常用,我在这儿只是尝试一下使用反射的方法:if v,ok:=item.(comper); ok{...}
不能直接对value类型进行大小比较:
value类型不能通过">"与"<"直接比较大小,即使我们知道他是简单类型。作者还没有找到简单的方法能直接转化值为简单类型并比较,因此采用了枚举的方法。若有更简便的方法,也请告知。
如果使用实例指针实现接口:
这是一个比较难以发现的问题,涉及到golang的类型系统。也就是说,如果我们实现Lessthen的方法是这样func (t*Myint) Lessthan (x Comper) bool,那么很有可能你的断言item类型就要失败了。我们可以看一下此时item的类型:
fmt.Println(reflect.TypeOf(t.data[0])) //main.XXX
这不是我们期待的,因为我们知道只有*T类型的方法集才是S和*S,而T类型的方法集只有S。很明显,main.XXX的方法集里不包括Lessthan方法,只有*main.XXX才包括。所以正确的使用方法是,在最初赋值的时候就赋值给指针类型:
mi := Myint(i)
mydata.Push(&mi)
多接口分层Demo
空接口其实只是一个特殊用例,我们将其推广后即可发现,我们可以定义多个接口,声明多种方法,实体实现了若干种方法便有权限调用若干函数:
例如我们可以赋予读取权限,写入权限与删除权限,来对应不同需求:
type Reader interface {
Read () interface{}
}
type Writer interface {
Write (Writer)
}
type ReadWriter interface {
Reader
Writer
}
type Remover interface {
Remove ()
}
type Sdata struct {
data []interface{}
}
func (t *Sdata)Get(i int)interface{}{
if len(t.data) == 0{return nil}
if reflect.TypeOf(t.data[0]).Implements(reflect.TypeOf(new(Reader)).Elem()) == true{
return t.data[i].(Reader).Read()
}
}
func (t *Sdata)Modify(i int, w Writer){
// if reflect.TypeOf(t.data[0]).Implements(reflect.TypeOf(new(ReadWriter)).Elem()) == true
if _,ok:=t.data[0].(ReadWriter);ok{
t.data[i].(Writer).Write(w)
}
}
//......
自定义Myint类型并实现Reader,Writer接口:
type Readint int
func (t Readint) Read() interface{}{
return int(t)
}
//---------------------------------------------
type Myint int
func (t Myint) Read() interface{}{
return int(t)
}
func (t *Myint) Write(w Writer){
*t = *w.(*Myint)
return
}
func main() {
mydata := Sdata{make([]interface{}, 1)}
var u,v Myint = 5,6
mydata.data[0] = &u
fmt.Println("Myint is ", mydata.Get(0))
mydata.Modify(0,&v)
fmt.Println("Myint is ", mydata.Get(0))
var ru Readint = 100
readdata := Sdata{make([]interface{}, 1)}
readdata.data[0] = &ru
fmt.Println("Readint is ", readdata.Get(0))
//var rv Readint = 101
readdata.Modify(0,&v) //事实上,如果传递rv则编译根本不会通过。
fmt.Println("Readint is ", readdata.Get(0))
}
运行结果:
Myint is 5
Myint is 6
Readint is 100
Readint is 100
说明:如果因为认为上述代码传递&rv根本不会通过编译而不去作类型检查,这是不可取的。因为对于空接口interface{}而言,无所谓实体的类型,只在乎是否实现方法,因此传递&v是合情合理的。另外,因为该Demo是一个简易版本,所以判断权限部分仅仅根据判断第0个元素的权限。事实上,判断权限应该在初始化时完成并将其存储在结构体变量中。
最后关于并发的问题,套用读写锁即可。过于简单不再通过Demo验证。
关于如何在Golang中利用接口实现泛型就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。