Go 泛型:无效的复合文字类型 T

Go generics: invalid composite literal type T

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: invalid composite literal type T

原因是什么?有什么办法可以解决吗?

代码link:https://go.dev/play/p/oRiH2AyaYb6

不确定您是否需要泛型...但让我们解决您的编译错误:

invalid composite literal type T

和关于 composite literal 的 Go 规范:

The LiteralType's core type T must be a struct, array, slice, or map type (the grammar enforces this constraint except when the type is given as a TypeName).

有问题的代码是:

type MessageParse[T proto.Message] struct {}

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

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

通用类型 T 受限于类型 proto.Message。查看类型 proto.Message (which is an alias for type protoreflect.ProtoMessage) 表明它是 Go interface 类型并且 NOT 是核心类型。因此它不能用于实例化复合文字。

您会在 non-Generics 示例中得到 same compilation error,例如:

type mytype interface {
    SomeMethod() error
}

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