interface - Golang接口(interface)不需要导入?

标签 interface go

如果您看一下 File 结构,它有一个 Read()Write() 函数,它们与io.Writerio.Reader 接口(interface)Read()Write() 函数。但是 io 包在 File 包中找不到(未导入)。这是否意味着接口(interface)根本不需要导入就可以使用?只要 Read() 定义与接口(interface)相同,就可以暗示它是 io.Writerio.Reader< 的一部分 接口(interface)?

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

操作系统:http://golang.org/pkg/os/

最佳答案

os 不导入包 io 因为 io.Reader 接口(interface)没有在包 os 中使用.

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

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

但是实现/满足一个接口(interface)不是这个接口(interface)的使用:任何类型只要有正确的方法就可以实现任何接口(interface)(甚至是 future 还没有发明 jet 的接口(interface))。

关于interface - Golang接口(interface)不需要导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17559133/

相关文章:

unit-testing - 为单个接口(interface)编写测试并为多个实现运行它们

c++ - 为什么我继承的接口(interface)不使用我的基类的覆盖?

c# - 传递接口(interface)而不是对象实例

json - 如何在 Golang 中创建字典列表?

go - 我如何告诉我的测试等待 goroutine 中的回调?

java - Java接口(interface)方法的正确实现方法

c++ - 菱形继承(钻石问题)两次派生 - 构造函数参数不同 - 找不到指定虚拟继承的基础

google-app-engine - Go - AppEngine - 性能

session - Revel - 在 session 中存储对象

gcc - 如何修复以下 Google Cloud Platform 部署错误? [错误 2]