douhuocuo9012 2011-06-22 06:04
浏览 51
已采纳

在Go中,当* Type调用方法时,如何创建接口?

Attempting to create an interface, but methods have *Type, not Type receivers

APOLOGIZE: was sleepy and mis-read error messages. Thought I was being block from creating the DB interface when in reality I was mis-using it. Sorry about that... will be more careful in the future!

type Char string

func (*Char) toType(v *string) interface{} {
        if v == nil {
                return (*Char)(nil)
        }
        var s string = *v
        ch := Char(s[0])
        return &ch
}
func (v *Char) toRaw() *string {
        if v == nil {
                return (*string)(nil)
        }
        s := *((*string)(v))
        return &s
}

from here I would like an interface that contains the methods toType and toRaw

type DB interface{
        toRaw() *string
        toType(*string) interface{}
}

does not work since the function receivers are pointers. I say this because when I try to use it I get the error.k

    Char does not implement DB (toRaw method requires pointer receiver)

Is there a way to create an interface from toType and toRaw, or do I need to backup and have the receivers be the types themselves and not pointers to types?

  • 写回答

2条回答 默认 最新

  • doukong1901 2011-06-22 07:55
    关注

    I don't understand what your problem is. Yes, the way you've written it, *Char conforms to the interface DB and Char doesn't. You can either

    1. change your code so that the methods operate on the non-pointer type Char directly (which will automatically also work for *Char too)
    2. only use *Char when you need something to be compatible with type DB
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?