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

标签 go struct dependencies code-injection

关闭。这个问题是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/

相关文章:

c++ - 如何创建一个指向指针数组的指针来构造?

使用 delve 的 Golang 核心转储分析抛出错误 'unrecognized core format'

dictionary - Go中的深度合并订单图

c++ - 如何初始化具有 const 变量的结构数组

node.js - 如何计算NodeJS项目中npm依赖使用的百分比?

c# - Visual Studio 不复制链接文件的目录

scala - Typesafe Play WS 作为 SBT 项目中的依赖项

Golang 内置简单的键/值存储 API?

go - Gin 错误 : listen tcp: lookup addr on : no such host

c - sizeof(*v) 在 C 中意味着什么?