为了账号安全,请及时绑定邮箱和手机立即绑定

具有通用变量的结构上的方法

具有通用变量的结构上的方法

Go
侃侃无极 2022-12-05 16:20:57
我有以下使用泛型的代码。我知道不能将泛型与方法一起使用,但可以与类型一起使用。从技术上讲,我的代码符合这两个限制,但我仍然遇到错误./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)}https://go.dev/play/p/9sWxXYmAcUH
查看完整描述

1 回答

?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

如果您想明确表示您实际上并未在函数中使用,则只需添加[T]到GenericCacheWrapperor的末尾即可。[_]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)

}

此规则在语言规范中定义:


泛型类型也可能有与之关联的方法。在这种情况下,方法接收者必须声明与泛型类型定义中存在的相同数量的类型参数。


但这背后的原因不是很清楚,也许是为了使编译器/类型检查的实现更容易。


相关:Go error: cannot use generic type without instantiation


查看完整回答
反对 回复 2022-12-05
  • 1 回答
  • 0 关注
  • 141 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号