如何避免将依赖项对所有模块中的所有包都可用?

huangapple go评论64阅读模式
英文:

How to avoid making dependencies available for all packages in the module?

问题

从.NET背景来看,我目前正在尝试将我的第一个Go项目调整为更符合Go典型项目结构的形式(类似于这个)。我不明白的是,如何避免依赖意外地进入不属于它们的包中。

假设我有一个由两部分组成的项目,一个名为foo的应用程序和一个模型。

  • 我的模型只有很少的依赖项
  • foo应用程序可能依赖于用于HTTP、日志记录、指标等的库。

项目的结构可能如下所示:

├── go.mod
├── go.sum
├── model
│   ├── person.go
│   └── address.go
├── cmd
│   └── runfoo
│       └── main.go
└── foolib
    └── applicationlogic.go

但是因为模块文件位于根目录,运行go get github.com/httplib将使httplib也可用于模型。这种方法有一些缺点:

  • 很容易(特别是使用VSCode的自动导入等功能)并且有时很容易要求在模型中使用httplib,即使它明显不属于模型。
  • 通过查看go.mod文件,我无法确定哪些依赖项是为模型而存在,哪些是为应用程序而存在。

现在,我可以使用非常细粒度的模块,并为开发添加一个go.work文件,但这感觉很难维护(并且与参考结构不一致)。

我如何避免使所有包都可用的依赖项,并且这样做是否可取?

英文:

Coming form a .NET background, I am currently trying to adjust my first go project to a more go-typical project structure (similar to this). The thing I don't understand is, how to avoid dependencies accidentally creeping into packages where they do not belong.

Suppose I have a project consisting of two parts, an app called foo and a model.

  • my model has very few dependencies
  • the foo app might have dependencies to libraries for http, logging, metrics, etc.

The project might look like this:

├── go.mod
├── go.sum
├── model
│   ├── person.go
│   └── address.go
├── cmd
│   └── runfoo
│       └── main.go
└── foolib
    └── applicationlogic.go

But because the module file is at the root, go get github.com/httplib will make httplib available also for the model. This approach has drawbacks:

  • It is very easy (especially with VSCode auto-import and the like) and sometimes tempting to require httplib in the model, even though it does definitively not belong there.
  • Looking at the go.mod, I can not determine which dependencies are for the model and which are for the app.

Now, I could use very fine-grained modules and add a go.work file for developing, but that feels like it will be hard to maintain (and is not aligned with the reference structure).

How can I avoid making dependencies available for all packages and is it advisable to do so?

答案1

得分: 1

如何避免将依赖项对所有软件包都可用?

你不能(只使用一个模块)。

是否建议这样做?

不,绝对不建议。

你所看到的“缺点”实际上并不会导致任何实际问题,也不会引起任何问题。

英文:

> How can I avoid making dependencies available for all packages [?]

You cannot (with one module).

> [...] and is it advisable to do so?

No, absolutely not.

The "drawbacks" you see aren't problematic at all and do not lead to any issues in practice.

huangapple
  • 本文由 发表于 2023年2月3日 18:05:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75334140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定