亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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)它編譯正常,但在像這樣運行時失?。簆anic: 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 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號