package main
import (
"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
uj5u.com熱心網友回復:
不確定您是否需要泛型...但讓我們解決您的編譯錯誤:
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
受限于 type proto.Message
。查看proto.Message型別(它是 protoreflect.ProtoMessage 型別的別名)表明它是 Gointerface
型別而不是核心型別。因此它不能用于實體化復合文字。
您將在非泛型示例中得到相同的編譯錯誤,例如:
type mytype interface {
SomeMethod() error
}
_ = &mytype{} // // ERROR: invalid composite literal type mytype
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470394.html