亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go 泛型:無效的復合文字類型 T

Go 泛型:無效的復合文字類型 T

Go
DIEA 2022-12-13 10:25:28
package mainimport (    "google.golang.org/protobuf/proto")type NetMessage struct {    Data []byte}type Route struct {}type AbstractParse interface {    Parse(*NetMessage) proto.Message}type MessageParse[T proto.Message] struct {}func (p *MessageParse[T]) Parse(message *NetMessage) proto.Message {    protoT := &T{}    if len(message.Data) > 0 {        err := proto.Unmarshal(message.Data, protoT)        if err != nil {            return nil        }    }    return protoT}當我嘗試對 Go 進行通用編碼時,我遇到了這個問題:./prog.go:23:13: 無效復合文字類型 T原因是什么?有什么辦法可以解決嗎?代碼鏈接: https: //go.dev/play/p/oRiH2AyaYb6
查看完整描述

1 回答

?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

不確定您是否需要泛型...但讓我們解決您的編譯錯誤:


invalid composite literal type T

以及關于復合文字的Go 規范:


LiteralType 的核心類型 T 必須是結構、數組、切片或映射類型(語法強制執行此約束,除非類型作為 TypeName 給出)。


有問題的代碼是:


type MessageParse[T proto.Message] struct {}


func (p *MessageParse[T]) Parse(message *NetMessage) proto.Message {


    protoT := &T{} // <- here

泛型類型T受限于類型proto.Message。查看類型proto.Message (它是類型protoreflect.ProtoMessage的別名)表明它是 Gointerface類型而不是核心類型。因此它不能用于實例化復合文字。


您會在非泛型示例中遇到相同的編譯錯誤,例如:


type mytype interface {

    SomeMethod() error

}


_ = &mytype{}  // // ERROR: invalid composite literal type mytype


查看完整回答
反對 回復 2022-12-13
  • 1 回答
  • 0 關注
  • 847 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號