为了账号安全,请及时绑定邮箱和手机立即绑定

Panic: 接口转换: * 不是接口 X: 缺少方法 xxx

Panic: 接口转换: * 不是接口 X: 缺少方法 xxx

Go
红颜莎娜 2022-09-12 20:50:23
我正在开发一个项目,使用来自Kafka的消息,使用消息包或json格式取消命令,构建它的sql并将它们插入到TDengine数据库中。接口定义为:type TaosEncoder interface {    TaosDatabase() string    TaosSTable() string    TaosTable() string    TaosTags() []interface{}    TaosCols() []string    TaosValues() []interface{}}对于名为 :Recordtype Record struct {    DeviceID  string        `json:"deviceID"` // for table name    Timestamp time.Time     `json:"timestamp"`    Cols      []interface{} `json:"cols"`}实现接口:func (r *Record) TaosCols() []string {    var tags []string    return tags}// other methods are implemented too方法将使用接口方法:func ToTaosBatchInsertSql(l []interface{}) (string, error) {    records := make([]string, len(l))    for i, t := range l {        // type TaosEncoderT = *TaosEncoder        record, err := ToTaosRecordSql(t.(TaosEncoder))        if err != nil {            return "", err        }        records[i] = record    }    return fmt.Sprintf("insert into %s", strings.Join(records, " ")), nil}将其用作:records := make([]interface{}, size)for i := 0; i < size; i++ {    item := <-q.queue # an channel of Record, defined as: queue chan interface{}    records[i] = item}sqlStr, err := utils.ToTaosBatchInsertSql(records)它编译正常,但在像这样运行时失败:panic: interface conversion: record.Record is not utils.TaosEncoder: missing method TaosColsgoroutine 71 [running]:xxx/pkg/utils.ToTaosBatchInsertSql(0xc000130c80, 0xc8, 0xc8, 0xc8, 0x0, 0x0, 0x0)但是当我更改记录的实现时 - 删除*func (r Record) TaosCols() []string {    var tags []string    return tags}然后它就起作用了。我已经告诉在接口实现中使用,所以问题是:*可以实现与 的接口吗?func (r Record) xxx如果没有,我该怎么办?
查看完整描述

2 回答

?
手掌心

TA贡献1942条经验 获得超3个赞

此错误的原因与类型的方法集有关。

假设一个类型具有接收器类型为 的方法和一些接收器类型为 的方法。TT*T

然后,如果变量的类型为 ,则它具有所有可用的方法,这些方法具有接收器的指针接收器,但没有接收器类型为 *T 的方法TT

如果一个变量是 类型 ,则它同时具有两组可用的方法,即具有接收器类型的方法和具有接收器类型的方法。*TT*T

在你的例子中,type没有方法,因此它不会完全实现接口。RecordTaosCols()TaosEncoder

如果将类型的变量转换为变量,则它具有所有可用方法,然后实现接口。Record*Record

方法集: 常见问题 (FAQ) - Go 编程语言

方法集于:Go 编程语言规范 - Go 编程语言


查看完整回答
反对 回复 2022-09-12
?
湖上湖

TA贡献2003条经验 获得超2个赞

A 与 的类型不同。如果使用指针接收器来定义实现接口的方法,则仅实现 。Record*Record*RecordTaosEncoder

基于此:

item := <-q.queue # an channel of Record

看起来您需要发送一个值 on ,而不是一个 。*Recordq.queueRecord


查看完整回答
反对 回复 2022-09-12
  • 2 回答
  • 0 关注
  • 111 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号