我正在開發一個項目,使用來自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個贊
此錯誤的原因與類型的方法集有關。
假設一個類型具有接收器類型為 的方法和一些接收器類型為 的方法。T
T
*T
然后,如果變量的類型為 ,則它具有所有可用的方法,這些方法具有接收器的指針接收器,但沒有接收器類型為 *T 的方法
。T
T
如果一個變量是 類型 ,則它同時具有兩組可用的方法,即具有接收器類型的方法和具有接收器類型的方法。*T
T
*T
在你的例子中,type沒有方法,因此它不會完全實現接口。Record
TaosCols()
TaosEncoder
如果將類型的變量轉換為變量,則它具有所有可用方法,然后實現接口。Record
*Record

湖上湖
TA貢獻2003條經驗 獲得超2個贊
A 與 的類型不同。如果使用指針接收器來定義實現接口的方法,則僅實現 。Record
*Record
*Record
TaosEncoder
基于此:
item := <-q.queue # an channel of Record
看起來您需要發送一個值 on ,而不是一個 。*Record
q.queue
Record
- 2 回答
- 0 關注
- 131 瀏覽
添加回答
舉報
0/150
提交
取消