关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。
想改进这个问题?将问题更新为 on-topic对于堆栈溢出。
1年前关闭。
Improve this question
我总共有 3 个包:repository、restrict 和 main。
在我的存储库包中,我有一个名为“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 结构的地址传递给它?
最佳答案
最有可能rule.Repository
是一个接口(interface),*RestrictionRuleRepository
type 恰好实现了该接口(interface)。
这是一个例子:
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作为开始使用接口(interface)的好地方。
关于go - 传递与 Golang 中指定的参数类型不同的参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62097212/