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

我正在开发一个项目,使用来自Kafka的消息,使用消息包或json格式取消命令,构建它的sql并将它们插入到TDengine数据库中。


接口定义为:


type TaosEncoder interface {

    TaosDatabase() string

    TaosSTable() string

    TaosTable() string

    TaosTags() []interface{}

    TaosCols() []string

    TaosValues() []interface{}

}

对于名为 :Record


type 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 TaosCols


goroutine 71 [running]:

xxx/pkg/utils.ToTaosBatchInsertSql(0xc000130c80, 0xc8, 0xc8, 0xc8, 0x0, 0x0, 0x0)

但是当我更改记录的实现时 - 删除*


func (r Record) TaosCols() []string {

    var tags []string

    return tags

}

然后它就起作用了。


我已经告诉在接口实现中使用,所以问题是:*

  1. 可以实现与 的接口吗?func (r Record) xxx

  2. 如果没有,我该怎么办?


红颜莎娜
浏览 112回答 2
2回答

手掌心

此错误的原因与类型的方法集有关。假设一个类型具有接收器类型为 的方法和一些接收器类型为 的方法。TT*T然后,如果变量的类型为 ,则它具有所有可用的方法,这些方法具有接收器的指针接收器,但没有接收器类型为 *T 的方法。TT如果一个变量是 类型 ,则它同时具有两组可用的方法,即具有接收器类型的方法和具有接收器类型的方法。*TT*T在你的例子中,type没有方法,因此它不会完全实现接口。RecordTaosCols()TaosEncoder如果将类型的变量转换为变量,则它具有所有可用方法,然后实现接口。Record*Record方法集: 常见问题 (FAQ) - Go 编程语言方法集于:Go 编程语言规范 - Go 编程语言

湖上湖

A 与 的类型不同。如果使用指针接收器来定义实现接口的方法,则仅实现 。Record*Record*RecordTaosEncoder基于此:item&nbsp;:=&nbsp;<-q.queue&nbsp;#&nbsp;an&nbsp;channel&nbsp;of&nbsp;Record看起来您需要发送一个值 on ,而不是一个 。*Recordq.queueRecord
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go