具有通用变量的结构上的方法
Method on struct with generic variable
我有以下使用泛型的代码。我知道不能将泛型与方法一起使用,但可以与类型一起使用。从技术上讲,我的代码符合这两个限制,但我仍然遇到错误
./main.go:12:9: cannot use generic type GenericCacheWrapper[T any] without instantiation
实例化在main函数的第一行。
有什么办法可以做到这一点?这可以被视为 Golang 错误吗?
import (
"encoding/json"
"fmt"
)
type GenericCacheWrapper[T any] struct {
Container T
}
func (c GenericCacheWrapper) MarshalBinary() (data []byte, err error) {
return json.Marshal(c.Container)
}
func (c GenericCacheWrapper) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, &c.Container)
}
func main() {
wrapper := GenericCacheWrapper[int]{Container: 4}
data, err := wrapper.MarshalBinary()
if err != nil {
panic(err)
}
fmt.Println(data)
}
如果您想清楚地表明您实际上没有在 T
中使用 T
函数。
package main
import (
"encoding/json"
"fmt"
)
type GenericCacheWrapper[T any] struct {
Container T
}
func (c GenericCacheWrapper[T]) MarshalBinary() (data []byte, err error) {
return json.Marshal(c.Container)
}
func (c GenericCacheWrapper[T]) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, &c.Container)
}
func main() {
wrapper := GenericCacheWrapper[int]{Container: 4}
data, err := wrapper.MarshalBinary()
if err != nil {
panic(err)
}
fmt.Println(data)
}
这条规则定义在language spec:
A generic type may also have methods associated with it. In this case, the method receivers must declare the same number of type parameters as present in the generic type definition.
但这背后的原因还不是很清楚,也许是为了更容易实施 compiler/type 检查。
相关:
我有以下使用泛型的代码。我知道不能将泛型与方法一起使用,但可以与类型一起使用。从技术上讲,我的代码符合这两个限制,但我仍然遇到错误
./main.go:12:9: cannot use generic type GenericCacheWrapper[T any] without instantiation
实例化在main函数的第一行。 有什么办法可以做到这一点?这可以被视为 Golang 错误吗?
import (
"encoding/json"
"fmt"
)
type GenericCacheWrapper[T any] struct {
Container T
}
func (c GenericCacheWrapper) MarshalBinary() (data []byte, err error) {
return json.Marshal(c.Container)
}
func (c GenericCacheWrapper) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, &c.Container)
}
func main() {
wrapper := GenericCacheWrapper[int]{Container: 4}
data, err := wrapper.MarshalBinary()
if err != nil {
panic(err)
}
fmt.Println(data)
}
如果您想清楚地表明您实际上没有在 T
中使用 T
函数。
package main
import (
"encoding/json"
"fmt"
)
type GenericCacheWrapper[T any] struct {
Container T
}
func (c GenericCacheWrapper[T]) MarshalBinary() (data []byte, err error) {
return json.Marshal(c.Container)
}
func (c GenericCacheWrapper[T]) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, &c.Container)
}
func main() {
wrapper := GenericCacheWrapper[int]{Container: 4}
data, err := wrapper.MarshalBinary()
if err != nil {
panic(err)
}
fmt.Println(data)
}
这条规则定义在language spec:
A generic type may also have methods associated with it. In this case, the method receivers must declare the same number of type parameters as present in the generic type definition.
但这背后的原因还不是很清楚,也许是为了更容易实施 compiler/type 检查。
相关: