Go 泛型:不支持的复合类型 T
时间:2024-02-11
浏览: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学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.27
11.27
热门专题
