英文:
I think I'm misunderstanding Go polymorphism/interfaces/structs
问题
我不明白为什么以下代码无法编译。
我对Go语言为什么说HistoryReader
没有正确实现IReader
感到困惑。HistoryBook
实现了IBook
。为什么在尝试将HistoryReader
添加到IReader
切片时,Read(book IBook)
和Read(book HistoryBook)
不能一起使用?
package main
type IReader interface {
Read(book IBook)
}
// HistoryReader implements IReader
type HistoryReader struct{}
func (r *HistoryReader) Read(book HistoryBook) {
// ...
}
type IBook interface{}
// HistoryBook implements IBook
type HistoryBook struct{}
func main() {
var readerSlice []IReader
_ = append(readerSlice, &HistoryReader{})
}
./main.go:28:26: cannot use &HistoryReader{} (value of type *HistoryReader) as type ReaderInterface in argument to append:
*HistoryReader does not implement ReaderInterface (wrong type for Read method)
have Read(book HistoryBook)
want Read(book BookInterface)
英文:
I don't understand why the following code does not compile.
I am confused why Go is saying HistoryReader
does not correctly implement IReader
. HistoryBook
implements IBook
. Why are Read(book Ibook)
and Read(book HistoryBook)
not acceptable together when trying to add a HistoryReader
to a slice of IReader
s?
package main
type IReader interface {
Read(book IBook)
}
// HistoryReader implements IReader
type HistoryReader struct{}
func (r *HistoryReader) Read(book HistoryBook) {
// ...
}
type IBook interface{}
// HistoryBook implements IBook
type HistoryBook struct{}
func main() {
var readerSlice []IReader
_ = append(readerSlice, &HistoryReader{})
}
./main.go:28:26: cannot use &HistoryReader{} (value of type *HistoryReader) as type ReaderInterface in argument to append:
*HistoryReader does not implement ReaderInterface (wrong type for Read method)
have Read(book HistoryBook)
want Read(book BookInterface)
答案1
得分: 6
IReader
要求Read
接受任何IBook
。
但是HistoryReader.Read
只接受一个HistoryBook
,而不是任何IBook
。因此,HistoryReader
不满足IReader
的要求。
英文:
IReader
requires that Read
takes any IBook
.
But HistoryReader.Read
only accepts a HistoryBook
, not any IBook
. Therefore, HistoryReader
does not satisfy IReader
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论