我是一个很长时间的python开发人员.我正在尝试Go,将现有的python应用程序转换为Go.它是模块化的,对我来说非常好.
在Go中创建相同的结构后,我似乎陷入了循环导入错误,比我想要的要多得多.从未在python中遇到任何导入问题.我甚至不必使用导入别名.所以我可能有一些循环导入在python中不明显.我实际上发现这很奇怪.
无论如何,我迷路了,试图在Go中解决这些问题.我已经读过接口可以用来避免循环依赖.但我不明白怎么做.我也没有找到任何这方面的例子.有人可以帮我吗?
当前的python应用程序结构如下:
/main.py
/settings/routes.py contains main routes depends on app1/routes.py, app2/routes.py etc
/settings/database.py function like connect() which opens db session
/settings/constants.py general constants
/apps/app1/views.py url handler functions
/apps/app1/models.py app specific database functions depends on settings/database.py
/apps/app1/routes.py app specific routes
/apps/app2/views.py url handler functions
/apps/app2/models.py app specific database functions depends on settings/database.py
/apps/app2/routes.py app specific routes
Run Code Online (Sandbox Code Playgroud)
settings/database.py具有通用功能connect(),可以打开数据库会话.因此,应用程序包调用中的应用程序将database.connect()打开一个数据库会话.
同样的情况是settings/routes.py它具有允许应用程序将其子路由添加到主路由对象的功能.
设置包更多地是关于函数而不是数据/常量.这包含应用程序包中的应用程序使用的代码,否则必须在所有应用程序中复制这些代码.因此,如果我需要更改路由器类,我只需要更改settings/router.py,应用程序将继续工作而不进行任何修改.
我的代码具有以下结构:
// $GOPATH/experiments/interfaceexport/printer/printer.go
package printer
import "fmt"
type ResourcePrinter interface {
PrintSomething()
}
type JSONPrinter struct {
IsGeneric bool
}
func (printer *JSONPrinter) PrintSomething() {
fmt.Println("JSON")
}
// $GOPATH/experiments/interfaceexporter/printerretriever/printerretriever.go
package printer
import "experiments/interfaceexporter/printer"
func GetPrinter() printer.ResourcePrinter {
return &printer.JSONPrinter{IsGeneric: true}
}
// $GOPATH/experiments/interfaceexport/main.go
import "experiments/intefaceexport/printerretriever"
func main() {
printer := printerretriever.GetPrinter()
printer.PrintSomething() // "JSON"
// interfaceexport/main.go:13: printer.IsGeneric undefined (type printer.ResourcePrinter has no field or method IsGeneric)
if printer.IsGeneric {
printer.PrintSomething()
}
}
Run Code Online (Sandbox Code Playgroud)
当我这样做时,go run main.go我得到以下错误:
interfaceexport/main.go:13: printer.IsGeneric undefined …
go ×2