【发布时间】:2023-02-09 05:04:49
【问题描述】:
假设我有两个不同的结构:
type One struct {
Id string
// Other fields
}
type Two struct {
Id string
// Other fields
}
是否可以定义一个同时接受 One 和 Two 的函数,而不明确将它们列为选项?
例如。我正在寻找这样的东西:
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