gpt4 book ai didi

go - 如何在 go 中排序不同结构类型的列表

转载 作者:IT王子 更新时间:2023-10-29 00:45:48 25 4
gpt4 key购买 nike

我使用 Go 才几天时间。我定义了一些不同的结构类型,每个结构类型都包含一个日期。

我需要以某种方式按日期顺序处理这些结构,但该顺序必须跨越多个不同的结构类型。在像 Python 这样的动态类型语言中,很容易创建所有按日期键控的对象的散列(或者列表的散列,如果它们不是唯一的)。在 C 中,我可以使用指针联合或 void*。但我不知道如何在 Go 中执行此操作。

我想我可以保留每种类型的排序列表,并在进行时进行手动合并排序。看起来很笨拙?

我读到的关于处理这种情况的内容似乎指向使用接口(interface),但我真的不知道如何在这种情况下使用它们。

为了争论,假设我有这样的东西:

type A struct {
Date string
Info string
}

type B struct {
Date string
Info int
}

(虽然在实践中有更多的结构,并且它们具有多个字段更复杂),并且只需要按日期顺序打印它们每个的(未排序的)数组的内容。

有什么方法可以创建非统一对象类型的列表(日期、指针)对吗?


根据下面的第一个建议:

package main
import "fmt"

type A struct {
Date string
Info string
}
func (x *A) GetDate() string {
return x.Date
}
type B struct {
Date string
Info int
}
func (x *B) GetDate() string {
return x.Date
}

type Dater interface {
GetDate() string
}

type Daters []Dater
func (s Daters) Len() int { return len(s) }
func (s Daters) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
type ByDate struct{ Daters }
func (s ByDate) Less(i, j int) bool {
return s.Daters[i].GetDate() < s.Daters[j].GetDate()
}

func main() {
// lista and listb are just examples. They really come from elsewhere
lista := []A{{"2012/08/01", "one"}, {"2012/08/03", "three"}}
listb := []B{{"2012/08/02", 2}, {"2012/08/04", 4}}

x := make([]Dater, len(lista) + len(listb))
index := 0
for i := range(lista) {
x[index] = &lista[i]
index++
}
for i := range(listb) {
x[index] = &listb[i]
index++
}
sort.Sort(ByDate{x})
for _,v := range(x) {
fmt.Printf("%#v\n", v)
}
}

行得通!所以接口(interface)的基本使用没问题,我开始明白了界面好一点 - 谢谢!

注意:x 的创建非常难看。我看不到更简洁/更惯用的方式吗?

最佳答案

用一个方法(比如返回日期的 getDate())定义一个接口(interface)(比如 Dated)。然后让所有结构(A、B、C)实现 Dated 接口(interface)。然后你可以定义使用 []Dated 来保存你的类型值。

您可能需要检查包“time”和“sort”以简化实现。

关于go - 如何在 go 中排序不同结构类型的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12452502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com