Golang之泛型編程-細節
阿新 • • 發佈:2018-08-05
UNC class urn make read lang 類型 error turn
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之泛型編程-細節