如何使嵌入的通用字段不可导出

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

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.

huangapple
  • 本文由 发表于 2023年5月8日 11:38:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76197374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定