我正在开发一个项目,使用来自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个赞
此错误的原因与类型的方法集有关。
假设一个类型具有接收器类型为 的方法和一些接收器类型为 的方法。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 关注
- 111 浏览
添加回答
举报
0/150
提交
取消