英文:
Import cycles more than two levels go
问题
所以我有一个需要解决的导入循环,并且我的项目结构基本上是这样的:
model.go -> procedure.go -> function.go
在我的函数中,我需要使用模型,并且我使用接口来处理它。目前我的代码基本上是这样的:
type imodel interface {
foo()
}
type model struct {
}
func (m *model) run() {
proc := &procedure{}
proc.run(m)
}
func (m *model) foo() {
//bla bla
}
type procedure struct {
}
func (p *procedure) run(model imodel) {
funct := &function{}
funct.run(model)
}
type function struct {
}
func (f *function) run(model imodel) {
model.foo()
}
我的问题是,我是否应该像这样通过接口在每个类中传递我的模型,还是有其他的解决方法?
英文:
So i have this import cycle to solve, and my project structure basically likes this:
> model.go -> procedure.go -> function.go
In my function i need model and i use interface to handle it. Currently my code basically like this:
type imodel interface {
foo()
}
type model struct {
}
func (m *model) run() {
proc := &procedure{}
proc.run(m)
}
func (m *model) foo() {
//bla bla
}
type procedure struct {
}
func (p *procedure) run(model imodel) {
funct := &function{}
funct.run(model)
}
type function struct {
}
func (f *function) run(model imodel) {
model.foo()
}
My question is should i pass my model using interface thorough every class like that or there's any other workaround?
答案1
得分: 3
我会将所有这些内容放在同一个包中。根据情况,我可能会将它们放在同一个包的不同文件中。
另外,你似乎没有导出imodel
,所以它将是包内部的内容,除非你有多个具体的实现,否则你不需要一个接口。然后,"imodel"不是一个理想的名称,接口应该被命名为model
,每个实现接口的具体类型应该根据其所模拟的内容进行命名。
英文:
I would put all of these in the same package. Depending on circumstances, I may put them in different files in the same package.
Also, you do not seem to export imodel
, so it would be package-internal and unless you have multiple concrete implementations, you do not need an interface. Then, "imodel" is a less than ideal name, the interface should be named model
and each concrete type implementing the interface should be named after what it models.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论