Golang之泛型编程-细节


Golang没有泛型<>,但是可以通过interface{}来接收各种类型值。

如下运用切片和泛型实例:

type Slice []interface{}

func NewSlice() Slice {
    return make(Slice, 0)
}

func (this* Slice) Add(elem interface{}) error {
    for _, v := range *this {
        if v == elem {
            fmt.Printf("Slice:Add elem: %v already exist\n", elem)
            return ERR_ELEM_EXIST
        }
    }
    *this = append(*this, elem)
    fmt.Printf("Slice:Add elem: %v succ\n", elem)
    return nil
}

func (this* Slice) Remove(elem interface{}) error {
    found := false
    for i, v := range *this {
        if v == elem {
            if i == len(*this) - 1 {
                *this = (*this)[:i]

            } else {
                *this = append((*this)[:i], (*this)[i+1:]...)
            }
            found = true
            break
        }
    }
    if !found {
        fmt.Printf("Slice:Remove elem: %v not exist\n", elem)
        return ERR_ELEM_NT_EXIST
    }
    fmt.Printf("Slice:Remove elem: %v succ\n", elem)
    return nil
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM