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 ", elem) return ERR_ELEM_EXIST } } *this = append(*this, elem) fmt.Printf("Slice:Add elem: %v succ ", 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 ", elem) return ERR_ELEM_NT_EXIST } fmt.Printf("Slice:Remove elem: %v succ ", elem) return nil }