How to define generic function with custom structs without listing all of them?

huangapple go评论80阅读模式
英文:

How to define generic function with custom structs without listing all of them?

问题

假设我有两个不同的结构体:

type One struct {
  Id string
  // 其他字段
}

type Two struct {
  Id string
  // 其他字段
}

是否有可能定义一个函数,可以接受OneTwo,而不需要显式地列出它们作为选项?

例如,我想要这样的函数:

type ModelWithId struct {
  Id string
}

func Test[M ModelWithId](m M) {
  fmt.PrintLn(m.Id)
}

one := One { Id: "1" }
Test(one) // 输出 1

我不想使用func Test[M One | Two](m M),因为我可能会有10个以上的结构体,我不想每次在代码库中添加新的结构体时都要回到函数中去修改。

英文:

Let's say I have two different structs:

type One struct {
  Id string
  // Other fields
}

type Two struct {
  Id string
  // Other fields
}

Is it possible to define a function that accepts both One and Two without explicitly listing them as options?

E.g. I am looking for something like this:

type ModelWithId struct {
  Id string
}

func Test[M ModelWithId](m M) {
  fmt.PrintLn(m.Id)
}

one := One { Id: "1" }
Test(one) // Prints 1

I don't want to use funcTest[M One | Two](m M), because I'll likely have 10+ structs and I don't want to come back to the function every time I add a new struct to the codebase.

答案1

得分: 3

泛型约束使用方法来限制类型参数的行为,因此您需要将代码重写为:

type One struct {
    id string
}

func (o *One) Id() string {
    return o.id
}

然后您的使用场景将变为

type ModelWithId interface {
    Id() string
}

func Test[M ModelWithId](m M) {
    fmt.Println(m.Id())
}
英文:

Generics constraints the type parameter behaviours using methods, so you need to rewrite your code as:

type One struct {
    id string
}

func (o *One) Id() string {
    return o.id
}

then your use site would become:

type ModelWithId interface {
    Id() string
}

func Test[M ModelWithId](m M) {
    fmt.Println(m.Id())
}

huangapple
  • 本文由 发表于 2022年12月21日 10:01:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/74870642.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定