英文:
Import specific package
问题
我正在尝试解决一个依赖问题:假设我想让我的 main.go 代码与数据库完全解耦,我创建了两个包:dummy 和 postgres。
/app/
-- main.go
/dummy/
-- dummy.go
/postgres/
-- postgres.go
一切都正常工作,我只需要在 main.go 中选择要导入的包,以获取不同的行为... 但是在构建 main.go 时是否有一种选择的方法?
如果有更符合惯例的方法来实现这一点,我当然非常感兴趣!
英文:
I'm trying to solve a dependency problem : let's say I want to keep the code in my main.go totally decoupled from my database, I created 2 packages for that : dummy & postgres.
/app/
-- main.go
/dummy/
-- dummy.go
/postgres/
-- postgres.go
Everything is working fine, I just have to select in my main.go which package I would like to import to get a behavior or another... but is there a way to choose that when building main.go ?
If there's a more idiomatic way to achieve this, I'm of course very interested !
答案1
得分: 0
你可以通过使用构建标签(build tags)来利用Go的条件构建,并针对main.go进行编译。
参考这篇文章(https://dave.cheney.net/2014/09/28/using-build-to-switch-between-debug-and-release),并付诸实践。
例如:
目录结构
build-tags
├── build-tags
├── dummy
│ └── dummy.go
├── main_dummy.go
├── main_postgres.go
└── postgres
└── postgres.go
示例实现:
dummy/dummy.go
package dummy
import "fmt"
func PrintName() {
fmt.Println("My name is dummy package")
}
postgres/postgres.go
package postgres
import "fmt"
func PrintName() {
fmt.Println("My name is postgres package")
}
main_dummy.go
// +build dummy
package main
import "build-tags/dummy"
func main() {
dummy.PrintName()
}
postgres.go
// +build postgres
package main
import "build-tags/postgres"
func main() {
postgres.PrintName()
}
现在让我们构建并针对dummy
标签进行目标编译,你也可以用同样的方式为postgres
标签进行操作。
go build --tags="dummy"
# 运行程序
./build-tags
My name is dummy package
英文:
You can utilize the Go conditional build via build tags and target your compilation of main.go.
Refer this article and put your thoughts into action.
For Example:
Directory structure
build-tags
├── build-tags
├── dummy
│   └── dummy.go
├── main_dummy.go
├── main_postgres.go
└── postgres
└── postgres.go
Sample implementation:
dummy/dummy.go
package dummy
import "fmt"
func PrintName() {
fmt.Println("My name is dummy package")
}
postgres/postgres.go
package postgres
import "fmt"
func PrintName() {
fmt.Println("My name is postgres package")
}
main_dummy.go
// +build dummy
package main
import "build-tags/dummy"
func main() {
dummy.PrintName()
}
postgres.go
// +build postgres
package main
import "build-tags/postgres"
func main() {
postgres.PrintName()
}
Now let's build targeting dummy
tag, same way you can do for postgres
tag.
go build --tags="dummy"
# run the program
./build-tags
My name is dummy package
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论