我觉得我对Go语言的多态性/接口/结构体有些误解。

huangapple go评论114阅读模式
英文:

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 IReaders?

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.

huangapple
  • 本文由 发表于 2022年12月19日 09:29:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/74845598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定