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
}

  

猜你喜欢

转载自www.cnblogs.com/sigmod3/p/9426757.html
今日推荐