传入与 Golang 中指定的参数类型不同的参数类型?
时间:2024-04-16
浏览:334
作者:佚名
珍惜时间,勤奋学习!今天给大家带来《传入与 Golang 中指定的参数类型不同的参数类型?》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!
问题内容
我总共有 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 是一个接口,而 *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 作为开始使用界面的好地方。
今天关于《传入与 Golang 中指定的参数类型不同的参数类型?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
