码迷,mamicode.com
首页 > 其他好文 > 详细

Golang之泛型编程-细节

时间:2018-08-05 19:41:03      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:lse   make   append   his   ace   func   rem   接收   move   

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
}

  

Golang之泛型编程-细节

标签:lse   make   append   his   ace   func   rem   接收   move   

原文地址:https://www.cnblogs.com/sigmod3/p/9426757.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!