Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 迭代结构集合(切片)的通用方法_Go - Fatal编程技术网

Go 迭代结构集合(切片)的通用方法

Go 迭代结构集合(切片)的通用方法,go,Go,我在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 g

我在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
}
有没有一种聪明的方法来创建一个函数getIds[]Idable,它可以接受实现了方法GetId的任何结构

使用可能对您有所帮助的设计模式

type Identifiable interface {
    GetId() int
}

func GatherIds(ys []Identifiable) []int {
    xs := make([]int, 0, len(ys))
    for _, i := range ys {
        xs = append(xs, i.GetId())
    }
    return xs
}
创建一个在类似切片的接口上工作的函数。然后根据具体类型的一部分创建新类型

希望代码比我的描述更清晰

还有一个比令人愉快的更多的样板,去泛型。。。总有一天。它最大的优点是不需要将新方法添加到Foo、Bar或任何您可能需要使用的未来类型中。

使用的设计模式可能会对您有所帮助

创建一个在类似切片的接口上工作的函数。然后根据具体类型的一部分创建新类型

希望代码比我的描述更清晰


还有一个比令人愉快的更多的样板,去泛型。。。总有一天。它最大的优点是不需要将新方法添加到Foo、Bar或任何您可能需要使用的未来类型。

[]即使Foo实现了可识别接口,也无法将Foo转换为[]可识别。输入:appendxs,i=>appendxs,i。GetId@deft_code我注意到它不能被铸造,因为它正在运行,但这是真的吗?您对此有什么了解吗?[]即使Foo实现了可识别接口,也不能将Foo转换为[]可识别。输入:appendxs,i=>appendxs,i。GetId@deft_code我注意到它不能被铸造,因为它正在运行,但这是真的吗?你有关于它的读物吗?为什么投反对票?这是一个完美的答案。我认为我只需要编写生成器,它就会工作:在这里使用嵌入是否有可能避免一次又一次地生成Len和GetId?为什么要向下投票?这是一个完美的答案。我认为我只需要编写生成器,它就会工作:这里是否有可能使用嵌入来避免一次又一次地生成Len和GetId?
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)))
}