duan39779 2014-02-25 12:42
浏览 31
已采纳

遍历结构的集合(切片)的通用方法

I have following code in Go:

type Foo struct { Id int }
type Bar struct { Id int }

func getIdsFoo(foos []Foo) {
  ids = make([]int, len(foos))
  // iterate and get all ids to ids array
}

func getIdsBar(bars []Bar) {
  ids = make([]int, len(bars))
  // iterate and get all ids to ids array
}

Is there a clever way to create a function getIds([]Idable) that can take any struct that have method GetId() implemented?

  • 写回答

2条回答 默认 最新

  • douwen0612 2014-02-25 19:29
    关注

    sort uses a design patter that might help you.

    Create a function that works on an slice-like interface. Then create new types based off of a slice of your concrete types.

    Hopefully, the code is more clear than my description. http://play.golang.org/p/TL6yxZZUWT

    type IdGetter interface {
        GetId(i int) int
        Len() int
    }
    
    func GetIds(ig IdGetter) []int {
        ids := make([]int, ig.Len())
        for i := range ids {
            ids[i] = ig.GetId(i)
        }
        return ids
    }
    
    type Foo struct{ Id int }
    
    type Bar struct{ Id int }
    
    type FooIdGetter []Foo
    
    func (f FooIdGetter) GetId(i int) int {
        return f[i].Id
    }
    
    func (f FooIdGetter) Len() int {
        return len(f)
    }
    
    type BarIdGetter []Bar
    
    func (b BarIdGetter) GetId(i int) int {
        return b[i].Id
    }
    
    func (b BarIdGetter) Len() int {
        return len(b)
    }
    
    func main() {
        var f = []Foo{{5}, {6}, {7}}
        var b = []Bar{{10}, {11}, {12}}
    
        fmt.Println("foo ids:", GetIds(FooIdGetter(f)))
        fmt.Println("bar ids:", GetIds(BarIdGetter(b)))
    }
    

    There is still a bit more boilerplate than is pleasant, (Go generics... someday). It's greatest advantage is that new methods do not need to be added to Foo, Bar, or any future type you may need to work with.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题