go语言中interface实现泛型编程

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]
}

转载于:https://my.oschina.net/yang1992/blog/474215

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值