zoukankan      html  css  js  c++  java
  • Golang之泛型编程-细节

    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
    }
    

      

  • 相关阅读:
    链接Oracle数据库
    Spring boot Mybatis
    Spring Boot 部署
    javaEE应用组件
    maven项目搭建步骤
    Spring Boot中Redis的使用
    Struts2 Hello,Wold
    使用JSON
    Spring中Quartz的配置
    Guice示例
  • 原文地址:https://www.cnblogs.com/sigmod3/p/9426757.html
Copyright © 2011-2022 走看看