实现和扩展来自不同包的接口

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

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 (
    &quot;fmt&quot;
	&quot;io&quot;
)

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(&quot;A&quot;)
}

func main() {
	list := [1]io.ReaderAt{Aaa{}} // Use Aaa object as io.ReaderAt type
    list[0].A() //Trying to use an extended type. &lt;&lt; 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(&amp;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(&amp;Aaa{})
a.A()

https://play.golang.org/p/0bl5djJ0im

huangapple
  • 本文由 发表于 2016年11月19日 01:11:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/40682578.html
匿名

发表评论

匿名网友

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

确定