传入与Golang中指定的参数类型不同的参数类型?
我一共有3个包:repository、restrict和main 在我的存储库包中,我有一个名为“RestrictionRuleRepository”的结构,定义为:传入与Golang中指定的参数类型不同的参数类型?,go,struct,dependencies,code-injection,Go,Struct,Dependencies,Code Injection,我一共有3个包:repository、restrict和main 在我的存储库包中,我有一个名为“RestrictionRuleRepository”的结构,定义为: type RestrictionRuleRepository struct { storage map[string]float64 } 在另一个包中,我定义了一个“NewService”函数: func NewService(repository rule.Repository) Service { retur
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函数不需要存储库类型,但我正在将RestrictionRuleRepository结构的地址传递给它吗?很可能是
规则。存储库
是一个接口,*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()
}
正如您在中所看到的,这可以很好地编译
我还建议将其作为开始使用界面的好地方。什么是
规则。存储库
?你还没有定义它,所以不可能回答你的问题。(从外观上看,它可能是一个界面,但最好是您定义它,而不是让人们猜测来回答您的问题)。