传递与Golang中指定的参数类型不同的参数类型?

问题描述 投票:0回答:1

我总共有3个软件包:存储库,限制和主要。

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

type RestrictionRuleRepository struct {
    storage map[string]float64
}

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

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

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

ruleRepo := repository.RestrictionRuleRepository{}

restrictionService := restrict.NewService(&ruleRepo)

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

go struct dependencies code-injection
1个回答
0
投票

[最有可能是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作为开始使用界面的好地方。

© www.soinside.com 2019 - 2024. All rights reserved.