golang 中 调用接口是调用接口的声明还是实现 如何调用一个声明和实现分别写在两个文件里的接口
时间: 2023-12-31 17:05:03 浏览: 33
在 Golang 中,调用一个接口时调用的是接口的声明,而不是接口的实现。
如果一个接口的声明和实现分别写在两个文件里,调用方式和在同一个文件中声明和实现的调用方式是一样的。只需要在调用时导入包含接口声明的文件即可。
假设接口的声明在 `interface.go` 文件中,如下所示:
```go
package myinterface
type MyInterface interface {
Method1() string
Method2() int
}
```
接口的实现在 `interface_impl.go` 文件中,如下所示:
```go
package myinterface
type MyInterfaceImpl struct{}
func (impl *MyInterfaceImpl) Method1() string {
return "This is Method1"
}
func (impl *MyInterfaceImpl) Method2() int {
return 10
}
```
在其他文件中调用这个接口时,需要导入 `myinterface` 包,并使用接口类型的变量来调用方法:
```go
package main
import (
"fmt"
"myinterface"
)
func main() {
var myInterface myinterface.MyInterface
myInterface = &myinterface.MyInterfaceImpl{}
fmt.Println(myInterface.Method1())
fmt.Println(myInterface.Method2())
}
```
注意,在导入包时需要使用接口声明的包名,而不是实现的包名。在这个例子中,导入 `myinterface` 包即可,不需要导入 `myinterface_impl` 包。