英文:
How to make embedded generic field unexported
问题
如果我不使用泛型,我可以使用下面的代码:
type otherType = external.OtherType
type MyType struct {
otherType
}
但是如果我使用泛型,它就无法工作,因为泛型类型不能被别名:
type otherType[T any] = external.OtherType[T] // 错误,泛型类型不能被别名
type MyType[T any] struct {
otherType[T]
}
我想要"覆盖"一个泛型类型的方法,但是我不想要嵌入字段的所有方法都被导出。
英文:
If I don't use generics, I can use this code below,
type otherType = external.OtherType
type MyType struct {
otherType
}
but if I use generics, It can't work, because generic type cannot be alias.
type otherType[T any] = external.OtherType[T] //error, generic type cannot be alias
type MyType[T any] struct {
otherType[T]
}
I want to "overide" a method of a generic type,but I don't want all methods of the embedded field to export.
答案1
得分: 2
这将在不久的将来可用:spec: generics: permit type parameters on aliases,该提案已经被接受。
截至今天(Go 1.20),你只能在泛型类型的实例化上定义类型别名:
type otherType = external.OtherType[string]
然而,请注意,即使类型本身未导出,嵌入类型的方法也会被提升。通过嵌入一个未导出的类型,你只是防止客户端包访问嵌入的字段。
有关一些解决方法,请参见这里。
英文:
It will be available in the not-so-distant future: spec: generics: permit type parameters on aliases, the proposal is already accepted.
As of today (Go 1.20) you can only define type aliases on instantiations of generic types:
type otherType = external.OtherType[string]
However note that methods of an embedded type get promoted even if the type itself is unexported. What you accomplish by embedding an unexported type is simply to prevent client packages to access the embedded field.
For some workaround, see https://stackoverflow.com/questions/44439087/export-only-subset-of-methods-implemented-by-embedded-struct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论