在C/C++中我们可以使用泛型的方法使代码得以重复使用,最常见例如stl functions:vector<int> vint or vector<float> vfloat等。这篇文章将使用interface{...}接口使Golang实现泛型。
interface{...}是实现泛型的基础。如一个数组元素类型是interface{...}的话,那么实现了该接口的实体都可以被放置入数组中。注意其中并不一定必须是空接口(简单类型我们可以通过把他转化为自定义类型后实现接口)。为什么interface中要声明方法:因为当我们需要对数组内数据进行操作时(如比较大小),我们需要为这个操作声明一个自定义的方法。换言之,只有实现了这个方法的实体才允许被加入进数组中。
基础Demo
在下面演示的Demo中,我们将实现一个最简单的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{...}









