2

If you take a look at the File struct it has a Read() and Write() function that is exactly the same as io.Writer and io.Reader interface Read() and Write() functions. But the package io is no where to be found in File package (not imported). Does this mean that interfaces do not at all have to be imported to be used? As long as the Read() definition is the same as the interface it can then be implied that it is part of the io.Writer or io.Reader interface?

io: http://golang.org/pkg/io/

os: http://golang.org/pkg/os/

4

2 回答 2

11

os不导入包io,因为包io.Reader中没有使用接口os

该类型*File恰好实现io.Reader,因为它有一个Read具有正确签名的方法。这实现关系是隐式的,既不需要也不可能使这种关系显式(例如,在 Java 中implements ISomeThing)。

您问:“这是否意味着根本不需要导入接口来使用?” 正式的答案是:当然不是!如果你想使用io.Reader你必须import "io"

但是实现/满足一个接口并不是使用这个接口:任何类型都可以通过拥有正确的方法来实现任何接口(甚至是未来尚未发明的接口)。

于 2013-07-09T22:58:24.317 回答
1

导出的实体是常量、变量和类型。使用它们,即。要引用此类导出的实体,必须使用它们的 [qualified] 名称,而限定符是导出它们的包的基本名称。这也意味着使用此类包的导入语句。IOW,在文件范围内绑定导出的实体是 [严格]显式的。没有导入 == 无法访问导出的内容。

OTOH,实现接口被指定隐式

一个类型实现了包含其方法的任何子集的任何接口,因此可以实现几个不同的接口。例如,所有类型都实现空接口:

interface{}
于 2013-07-09T22:19:26.293 回答