美文网首页
golang 泛型自定义数组

golang 泛型自定义数组

作者: 吃猫的鱼0 | 来源:发表于2018-02-22 16:09 被阅读0次

    代码

    package slice
    
    import (
        "fmt"
        "errors"
    )
    
    type Slice []interface{}
    
    func NewSlice() Slice {
        return make(Slice, 0)
    }
    
    func (this* Slice) Add(elem interface{}) error {
        for _, v := range *this {
            if isEqual(v, elem) {
                fmt.Printf("Slice:Add elem: %v already exist\n", elem)
                return errors.New("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 isEqual(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 errors.New("ERR_ELEM_NT_EXIST")
        }
        fmt.Printf("Slice:Remove elem: %v succ\n", elem)
        return nil
    }
    func isEqual(a, b interface{}) bool {
        if comparable, ok := a.(Comparable); ok {
            return comparable.IsEqual(b)
        } else {
            return a == b
        }
    }
    type Comparable interface {
        IsEqual(obj interface{}) bool
    }
    

    对象demo

    type Student struct {
        id string
        name string
    }
    func (this Student) IsEqual(obj interface{}) bool {
        if student, ok := obj.(Student); ok {
            return this.GetId() == student.GetId()
        }
        panic("unexpected type")
    }
    
    func (this Student) GetId() string {
        return this.id
    }

    相关文章

      网友评论

          本文标题:golang 泛型自定义数组

          本文链接:https://www.haomeiwen.com/subject/xyrztftx.html