首页 > 编程语言 > 详细

go语言中interface实现泛型编程

时间:2015-07-03 16:15:44      阅读:405      评论:0      收藏:0      [点我收藏+]

package main

import (
“fmt”
“reflect”
)

type GenericSlice struct {
elemType reflect.Type
sliceValue reflect.Value
}

func (self *GenericSlice) Init(sample interface{}) {
value := reflect.ValueOf(sample)
self.sliceValue = reflect.MakeSlice(value.Type(), 0, 0)
self.elemType = reflect.TypeOf(sample).Elem()
}

func (self *GenericSlice) Append(e interface{}) bool {
if reflect.TypeOf(e) != self.elemType {
return false
}
self.sliceValue = reflect.Append(self.sliceValue, reflect.ValueOf(e))
return true
}

func (self *GenericSlice) ElemType() reflect.Type {
return self.elemType
}

func (self *GenericSlice) Interface() interface{} {
return self.sliceValue.Interface()
}

func main() {
gs := GenericSlice{}
gs.Init(make([]int, 0))
fmt.Printf(“Element Type: %s\n”, gs.ElemType().Kind()) // => Element Type:int result := gs.Append(2)
fmt.Printf(“Result: %v\n”, result) // => Result: true
fmt.Printf(“sliceValue: %v\n”, gs.Interface()) // => sliceValue: [2]
}

go语言中interface实现泛型编程

原文:http://my.oschina.net/u/932809/blog/474215

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!