golang 泛型自定义数组

2018-02-22  本文已影响0人  吃猫的鱼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
}
上一篇下一篇

猜你喜欢

热点阅读