文章目录
Go接口
接口的本质是引入一个中间层,上层的调用方不再需要依赖下层的具体模块,只需要依赖一个定义好的接口
Go中的接口是一种内置类型,定义了一组方法的集合
在Java中我们在接口中可以定义变量,也可以定义方法签名
public interface MyInterface {
public String hello = "Hello";
public void sayHello();
}
通过implements 关键字显示的实现接口
public class MyInterfaceImpl implements MyInterface {
public void sayHello() {
System.out.println(MyInterface.hello);
}
}
go中的接口也是用interface关键字声明,但是只能声明方法,不能定义变量
type error interface {
Error() string
}
在go中实现一个接口只需要实现接口里的方法即可
type RPCError struct {
Code int64
Message string
}
func (e *RPCError) Error() string {
return fmt.Sprintf("%s, code=%d", e.Message, e.Code)
}
在结构体上没有Error接口的身影,go中实现接口是隐性的,Go 语言只会在传递参数、返回参数以及变量赋值时才会对某个类型是否实现接口进行检查