Go中传入与指定类型不同的参数为何可正常编译?
为什么Go允许传入
RestrictionRuleRepository指针给期望Repository接口的函数? 这事儿的核心原因在于Go的接口是隐式实现的——这和Java、C#这类需要显式声明implements的语言完全不同,也是Go的一大特性。
咱们拆解来看你的代码场景:
- 首先
rule.Repository肯定是一个接口类型(虽然你没贴它的定义,但从代码能推断出来),它应该包含了一组方法签名,比如可能是这样:type Repository interface { // 示例方法,根据你的Repository结构体功能推测 GetLimit(key string) float64 SetLimit(key string, value float64) } - 你的
RestrictionRuleRepository结构体的指针类型(也就是*RestrictionRuleRepository),刚好实现了rule.Repository接口要求的所有方法——可能你在代码里写了类似这样的方法:func (r *RestrictionRuleRepository) GetLimit(key string) float64 { return r.storage[key] } func (r *RestrictionRuleRepository) SetLimit(key string, value float64) { r.storage[key] = value } - Go编译器会自动检查类型的方法集:只要一个类型的方法集完全覆盖了某个接口的所有方法,这个类型就被视为实现了该接口,不需要你做任何额外声明。
回到你的代码:
ruleRepo := repository.RestrictionRuleRepository{}创建了一个值类型的实例&ruleRepo是这个实例的指针,也就是*RestrictionRuleRepository类型,它的方法集刚好匹配rule.Repository接口- 所以
restrict.NewService(&ruleRepo)完全符合函数参数要求,编译器自然不会报错
补充个小知识点:如果你的方法是定义在值接收器上(比如func (r RestrictionRuleRepository) GetLimit(...)),那值类型RestrictionRuleRepository和指针类型*RestrictionRuleRepository都会实现接口;但如果方法是定义在指针接收器上,只有指针类型能实现接口,值类型不行。
内容的提问来源于stack exchange,提问作者David Pham
相关产品推荐
相关产品推荐

