【问题标题】:How to define generic function with custom structs without listing all of them?如何在不列出所有自定义结构的情况下定义通用函数?
【发布时间】:2023-02-09 05:04:49
【问题描述】:

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

type One struct {
  Id string
  // Other fields
}

type Two struct {
  Id string
  // Other fields
}

是否可以定义一个同时接受 OneTwo 的函数,而不明确将它们列为选项?

例如。我正在寻找这样的东西:

type ModelWithId struct {
  Id string
}

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

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

我不想使用 funcTest[M One | Two](m M),因为我可能会有 10 多个结构,而且我不想每次向代码库添加新结构时都回到该函数。

【问题讨论】:

    标签: go generics constraints


    【解决方案1】:

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

    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())
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多