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

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

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

问题

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

  1. type One struct {
  2. Id string
  3. // 其他字段
  4. }
  5. type Two struct {
  6. Id string
  7. // 其他字段
  8. }

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

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

  1. type ModelWithId struct {
  2. Id string
  3. }
  4. func Test[M ModelWithId](m M) {
  5. fmt.PrintLn(m.Id)
  6. }
  7. one := One { Id: "1" }
  8. Test(one) // 输出 1

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

英文:

Let's say I have two different structs:

  1. type One struct {
  2. Id string
  3. // Other fields
  4. }
  5. type Two struct {
  6. Id string
  7. // Other fields
  8. }

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:

  1. type ModelWithId struct {
  2. Id string
  3. }
  4. func Test[M ModelWithId](m M) {
  5. fmt.PrintLn(m.Id)
  6. }
  7. one := One { Id: "1" }
  8. 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

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

  1. type One struct {
  2. id string
  3. }
  4. func (o *One) Id() string {
  5. return o.id
  6. }
  7. 然后您的使用场景将变为
  8. type ModelWithId interface {
  9. Id() string
  10. }
  11. func Test[M ModelWithId](m M) {
  12. fmt.Println(m.Id())
  13. }
英文:

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

  1. type One struct {
  2. id string
  3. }
  4. func (o *One) Id() string {
  5. return o.id
  6. }

then your use site would become:

  1. type ModelWithId interface {
  2. Id() string
  3. }
  4. func Test[M ModelWithId](m M) {
  5. fmt.Println(m.Id())
  6. }

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:

确定