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?
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()