将Go包的导入分割到不同的文件中。

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

Imports for Go package splitted into files

问题

如果我需要在Go语言中的两个或多个文件中为一个包导入同一个包,那么惯用的方式是什么?

直到今天,我是这样做的:

file1.go

package A

import "os"

file2.go

package A

import "os"
英文:

If I need an import in two or more files for one package in Go, what is the idiomatic way?

Until today I do it like this:

file1.go

package A

import "os"

file2.go

package A

import "os"

答案1

得分: 4

这不是一个关于是否符合习惯用法的问题,而是一个关于作用域的问题。

导入声明的作用域限定在包含它的文件中。规范:导入声明

导入声明表示包含该声明的源文件依赖于导入包的功能(§程序初始化和执行),并且可以访问该包的导出标识符。

还有规范:声明和作用域

Go使用进行词法作用域:
...
3. 导入包的包名的作用域是包含导入声明的文件块。
...

这意味着,如果有一个在多个文件中需要的包(无论是形成单个包还是多个包),你必须在所有这些文件中单独导入它。

你应该检查和修改如何在文件之间分离代码,因为这可能是一种将具有相同依赖关系(依赖于相同一组包)的函数和声明分组到同一个文件中的好方法,这样你只需要导入这些包一次。

还要注意,如果mypkg包的某些文件依赖于一组其他包,但不依赖于mypkg的其他文件,将mypkg拆分为基于依赖关系的两个独立包也可能是有利的。大多数这些决策都是主观的,你需要判断它们在你的情况下是否合理。

英文:

It's not a question of being idiomatic, it's a question of scopes.

Import declarations are scoped to the containing file. Spec: Import declarations:

> An import declaration states that the source file containing the declaration depends on functionality of the imported package (§Program initialization and execution) and enables access to exported identifiers of that package.

Also Spec: Declarations and scope:

> Go is lexically scoped using blocks:
> ...
> 3. The scope of the package name of an imported package is the file block of the file containing the import declaration.
> ...

What this means is that if there's a package that is needed in multiple files (forming a single package or multiple, it doesn't matter), you have to import it separately in all of those files.

What you should do is review and revise how you separate code between files, because it may be a good way to group functions and declarations into the same file that have the same dependencies (that depend on the same set of packages), and so you would only need to import those packages once.

Also note that if certain files of package mypkg depend on a set of other packages, but not the other files of mypkg, it may also be profitable to split mypkg into 2 separate packages based on the dependencies. Most of these decisions are subjective though, you have tell if they make sense in your case or not.

huangapple
  • 本文由 发表于 2017年2月13日 04:35:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/42192925.html
匿名

发表评论

匿名网友

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

确定