文章目錄
- Go接口
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
}
type RPCError struct {
Code int64
Message string
}
func (e *RPCError) Error() string {
return fmt.Sprintf("%s, code=%d", e.Message, e.Code)
}