You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go中传入与指定类型不同的参数为何可正常编译?

为什么Go允许传入RestrictionRuleRepository指针给期望Repository接口的函数?

这事儿的核心原因在于Go的接口是隐式实现的——这和Java、C#这类需要显式声明implements的语言完全不同,也是Go的一大特性。

咱们拆解来看你的代码场景:

  1. 首先rule.Repository肯定是一个接口类型(虽然你没贴它的定义,但从代码能推断出来),它应该包含了一组方法签名,比如可能是这样:
    type Repository interface {
        // 示例方法,根据你的Repository结构体功能推测
        GetLimit(key string) float64
        SetLimit(key string, value float64)
    }
    
  2. 你的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
    }
    
  3. Go编译器会自动检查类型的方法集:只要一个类型的方法集完全覆盖了某个接口的所有方法,这个类型就被视为实现了该接口,不需要你做任何额外声明。

回到你的代码:

  • ruleRepo := repository.RestrictionRuleRepository{} 创建了一个值类型的实例
  • &ruleRepo 是这个实例的指针,也就是*RestrictionRuleRepository类型,它的方法集刚好匹配rule.Repository接口
  • 所以restrict.NewService(&ruleRepo)完全符合函数参数要求,编译器自然不会报错

补充个小知识点:如果你的方法是定义在值接收器上(比如func (r RestrictionRuleRepository) GetLimit(...)),那值类型RestrictionRuleRepository和指针类型*RestrictionRuleRepository都会实现接口;但如果方法是定义在指针接收器上,只有指针类型能实现接口,值类型不行。

内容的提问来源于stack exchange,提问作者David Pham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:57:46