英文:
How to define generic function with custom structs without listing all of them?
问题
假设我有两个不同的结构体:
type One struct {
Id string
// 其他字段
}
type Two struct {
Id string
// 其他字段
}
是否有可能定义一个函数,可以接受One
和Two
,而不需要显式地列出它们作为选项?
例如,我想要这样的函数:
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())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论