标签:
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]
}
标签:
原文地址:http://my.oschina.net/u/932809/blog/474215