【问题标题】:Passing in a different parameter type than the one specified works in Golang? [closed]传递与 Golang 中指定的参数类型不同的参数类型? [关闭]
【发布时间】:2020-09-17 16:29:49
【问题描述】:

我总共有 3 个包:repository、restrict 和 main。

在我的存储库包中,我有一个名为“RestrictionRuleRepository”的结构,定义为:

type RestrictionRuleRepository struct {
    storage map[string]float64
}

在另一个包限制中,我定义了一个“NewService”函数:

func NewService(repository rule.Repository) Service {
    return &service{
        repository: repository,
    }
}

最后,在我的 main 包中,我有这两行代码:

ruleRepo := repository.RestrictionRuleRepository{}

restrictionService := restrict.NewService(&ruleRepo)

我的代码正在编译,没有任何错误。为什么在 Golang 中允许这样做?我的 NewService 函数不需要 Repository 类型,但我将 RestrictionRuleRepository 结构的地址传递给它吗?

【问题讨论】:

  • 什么是rule.Repository?您尚未在任何地方定义它,因此无法回答您的问题。 (从外观上看它可能是一个界面,但最好由您定义它而不是让人们猜测试图回答您的问题)。

标签: go struct dependencies code-injection


【解决方案1】:

rule.Repository 很可能是一个接口,而*RestrictionRuleRepository 类型恰好实现了该接口。

这是一个例子:

package main

import (
    "fmt"
)

type Repository interface {
    SayHi()
}

type RestrictionRuleRepository struct {
    storage map[string]float64
}

func (r *RestrictionRuleRepository) SayHi() {
    fmt.Println("Hi!")
}

type service struct {
    repository Repository
}

type Service interface {
    MakeRepoSayHi()
}

func NewService(repository Repository) Service {
    return &service{
        repository: repository,
    }
}

func (s *service) MakeRepoSayHi() {
    s.repository.SayHi()
}

func main() {
    ruleRepo := RestrictionRuleRepository{}
    restrictionService := NewService(&ruleRepo)
    restrictionService.MakeRepoSayHi()
}

正如您在https://play.golang.org/p/bjKYZLiVKCh 中看到的那样,它编译得很好。

我还推荐 https://tour.golang.org/methods/9 作为开始使用接口的好地方。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 2021-12-17
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多