分享
Golang之泛型编程-细节
sigmod3 · · 1761 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
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
}
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信1761 次点击
下一篇:并发与锁
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
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
}