这是一个go语言的问题
首先我有这样一个interface
type TransactionReader interface {
TransactionByHash(ctx context.Context, txHash common.Hash) (tx *types.Transaction, isPending bool, err error)
TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
}
然后我有这样一个struct
type Client struct{
c *rpc.Client
}
最后我看到这样的调用:
_ = ethereum.TransactionReader(&Client{})
代码出自:https://github.com/ethereum/go-ethereum
问题是:这个借口的类型作为方法可以传参,执行的结果是什么? 只能传输这个参数,其他参数无效,这个参数类型又是如何定义的?在哪定义的
接口是双方约定的一种合作协议,接口定义不需要关心接口会被怎样使用,调用也不需要关心接口的实现细节。接口是一种类型,也是一种抽象结构,不会暴露所含数据格式、类型及结构。简单说接口就是是函数的集合,只要将结构体实例化变量的指针赋值给接口变量,就可以通过接口调用里面的方法,不妨看看下面例子
package main
import "fmt"
// 定义接口
type actions interface {
// 没有参数没有返回值
walk()
// 没有参数有返回值
runs() (int, int)
// 有参数没有返回值
speak(content string, speed int)
// 有参数有返回值
rest(sleepTime int) int
}
// 定义结构体
type cats struct {
name string
}
// 定义接口方法的功能逻辑
func (c *cats) walk() {
fmt.Printf("%v在散步\n", c.name)
}
func (c *cats) runs() (int, int) {
fmt.Printf("%v在跑步\n", c.name)
speed := 10
time := 1
return speed, time
}
func (c *cats) speak(content string, speed int) {
fmt.Printf("%v在说话:%v,语速:%v\n", c.name, content, speed)
}
func (c *cats) rest(sleepTime int) int {
fmt.Printf("%v在休息,入睡时间:%v小时\n", c.name, sleepTime)
return sleepTime
}
func main() {
// 定义接口变量
var a actions
// 结构体实例化
c := cats{name: "kitty"}
// 结构体实例化变量的指针赋值给接口变量
a = &c
// 调用接口里的方法
a.walk()
speed, time := a.runs()
fmt.Printf("跑步速度:%v,跑步时间:%v\n", speed, time)
a.speak("喵喵", 2)
sleepTime := a.rest(10)
fmt.Printf("入睡时间:%v小时\n", sleepTime)
}