drqvr26084 2016-11-25 13:20 采纳率: 100%
浏览 23
已采纳

在Go中,如何将某个接口的切片传递给期望有其他兼容接口的切片? [重复]

This question already has an answer here:

I have two interfaces, A and B. It happens that A includes B. Finally, I have a concrete implementation of A (call it Impl), which, by definition, also implements B.

For example:

type A interface {
    Close() error
    Read(b []byte) (int, error)
}

type Impl struct {}
func (I Impl) Read(b []byte) (int, error) {
    fmt.Println("In read!")
    return 10, nil
}
func (I Impl) Close() error {
    fmt.Println("I am here!")
    return nil
}

Since A requires Read(), and Impl implements A, it also satisfies io.Reader.

If I try to pass individual items across functions, it works fine. But if I try slices of A to functions expecting io.Reader, it fails.

Example:

func single(r io.Reader) {
    fmt.Println("in single")
}
func slice(r []io.Reader) {
    fmt.Println("in slice")
}
im := &Impl{}

// works
single(im)

// FAILS!
list := []A{t}
slice(list)

If I can pass an A to single(r io.Reader), why can I not pass []A to slice(r []io.Reader), and how would I correct it?

Actual implementation at https://play.golang.org/p/QOREQJTQhD just uncomment the last two lines in main() and the error shows:

main.go:38: cannot use list (type []A) as type []io.Reader in argument to slice
</div>
  • 写回答

1条回答 默认 最新

  • dongyuan1983 2016-11-25 13:26
    关注

    I kind of asked something similar here In Go, how can I make a generic function with slices?

    Sadly, this is definitely a weakness in Go. The only way for you to go around this is to make a new slice of type []io.Reader with elements from []A

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

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊