英文:
Implementation and extending interfaces from different packages
问题
我想知道是否可以扩展现有的接口?这里有一段简单的代码片段,但它无法工作。
package main
import (
"fmt"
"io"
)
type Aaa struct {}
// 实现 io.ReaderAt 接口
func (a Aaa)ReadAt(p []byte, off int64) (n int, err error) {
return
}
// 扩展接口
func (a *Aaa) A() {
fmt.Println("A")
}
func main() {
list := [1]io.ReaderAt{Aaa{}} // 将 Aaa 对象用作 io.ReaderAt 类型
list[0].A() // 尝试使用扩展类型。<< 错误发生在这里
}
list[0].A 未定义(类型 io.ReaderAt 没有字段或方法 A)
这是一种告诉我无法实现来自不同包的接口的方式吗?
英文:
I'm wondering, is it possible to extend existing interfaces? There is a simple code snippet which doesn't work.
package main
import (
"fmt"
"io"
)
type Aaa struct {}
// Implementing io.ReaderAt interface
func (a Aaa)ReadAt(p []byte, off int64) (n int, err error) {
return
}
// Extending it
func (a *Aaa) A() {
fmt.Println("A")
}
func main() {
list := [1]io.ReaderAt{Aaa{}} // Use Aaa object as io.ReaderAt type
list[0].A() //Trying to use an extended type. << Error occurred here
}
> list[0].A undefined (type io.ReaderAt has no field or method A)
Is it a way to tell me that I can't implement interfaces from different package?
答案1
得分: 6
只是告诉你io.ReaderAt没有A()方法。
你需要使用类型断言从io.ReaderAt中获取*Aaa。
a := io.ReaderAt(&Aaa{})
if a, ok := a.(*Aaa); ok {
a.A()
}
接口不需要在特定的位置定义,所以如果你的代码需要具有这些方法的ReaderAtA,你可以自己定义它,而任何ReaderAtA值也将是io.ReaderAt。
type ReaderAtA interface {
io.ReaderAt
A()
}
a := ReaderAtA(&Aaa{})
a.A()
链接:https://play.golang.org/p/0bl5djJ0im
英文:
It's only telling you that io.ReaderAt doesn't have an A() method.
You need a type assertion to get an *Aaa out of the io.ReaderAt.
a := io.ReaderAt(&Aaa{})
if a, ok := a.(*Aaa); ok {
a.A()
}
Interfaces don't need to be defined in any particular place, so if your code needs a ReaderAtA with those methods, you could define it yourself, and any ReaderAtA value would also be an io.ReaderAt
type ReaderAtA interface {
io.ReaderAt
A()
}
a := ReaderAtA(&Aaa{})
a.A()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论