duanhuo0577 2019-04-13 06:58
浏览 50
已采纳

即使同一接口也不能将X类型用作Y类型

I am trying to write a function which takes anything that implements a certain interface as an argument.

I have defined an interface KeyProvider which specifies a GetKey() method. I have defined a function that uses this interface ToKeys().

type KeyProvider interface {
    GetKey() *datastore.Key 
}

func ToKeys(l []*KeyProvider) []*datastore.Key {
    keys := make([]*datastore.Key, len(l))
    for i, vp := range l {
        v := *vp
        keys[i] = v.GetKey()
    }
    return keys
}

I have implemented this interface on a struct User.

type User struct {
    Key *datastore.Key
}

func (u *User) GetKey() *datastore.Key {
    return u.Key
}

I try to use the ToKeys() method.

func foo(users []*User) {
    keys := ToKeys(users)
}

But I get this error:

cannot use users (type []*User) as type []*KeyProvider in argument to ToKeys

Why? And how can I get something like this working?

  • 写回答

1条回答 默认 最新

  • 普通网友 2019-04-13 07:55
    关注

    always keep in mind, Go requires explicit type conversions.

    1.func ToKeys(l []*KeyProvider) []*datastore.Key should be func ToKeys(l []KeyProvider) []*datastore.Key.
    should almost never use pointer to an interface, use interface.

    2.not allow to convert []*User to []KeyProvider directly, because of different representation in memory (if you are interesting about slice's internal).

    you need to convert the slice manually, for example:

    func foo(t []*User) {
        s := make([]KeyProvider, len(t))
        for i, v := range t {
            s[i] = v
        }
    
        keys := ToKeys(s)
    }
    

    check this two urls:
    https://golang.org/doc/faq#convert_slice_of_interface https://golang.org/doc/faq#convert_slice_with_same_underlying_type

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向