登录
首页 >  Golang >  Go问答

Go 泛型:不支持的复合类型 T

来源:stackoverflow

时间:2024-02-11 18:33:23 444浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《Go 泛型:不支持的复合类型 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:无效的复合文字类型 t

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

代码链接:https://go.dev/play/p/orih2ayayb6


正确答案


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

invalid composite literal type t

以及关于 composite literal 的 go 规范:

literaltype 的核心类型 t 必须是结构体、数组、切片或映射 类型(语法强制执行此约束,除非类型为 作为类型名称给出)。

有问题的代码是:

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 的别名)表明它是 go interface 类型,而不是核心类型。因此它不能用于实例化复合文字。

您将在非泛型示例中获得 same compilation error,例如:

type mytype interface {
    SomeMethod() error
}

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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>