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
- 1 回答
- 0 關注
- 847 瀏覽
添加回答
舉報
0/150
提交
取消