relationship between directory structure and packages in golang

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

relationship between directory structure and packages in golang

问题

我是新手,对Golang的包的概念有一定的了解,但对它们与文件夹/目录位置的关系有些疑问。

我正在处理一个相当大的项目,其中包含/pkg目录下的多个子目录。可能有30多个不同的package ___命名空间声明。

通常情况下,目录中的所有文件都将具有相同的包,例如/pkg/system/api-client目录中的所有文件都声明为package apiclient

问题出现在我注意到两个package config的文件上;一个位于/pkg/config/config.go,另一个位于/pkg/writer-job/pkg/config/config.go

它们属于同一个包吗?如果是的话,这种做法的约定是什么(因为看起来相当分散)?如果不是的话,你如何在词法上将config分为两个独立的包?我查阅了文档,但没有找到相关内容。

英文:

I am new to Golang and grasp the concept of packages fairly well, but have a question about their relationship to folder/directory location.

So I am working on a fairly large project with multiple subdirectories inside the /pkg directory. There are probably 30+ distinct package ___ namespaces declared.

Typically of course all files inside of a directory will have the same package, e.g. /pkg/system/api-client; all files in that directory are declared package apiclient

The question arises when I notice two files of package config; one is in /pkg/config/config.go and the other is /pkg/writer-job/pkg/config/config.go.

Are they part of the same package? If so, what is the convention for this (as it seems quite scattered)? And if not, how do you lexically separate config as two separate packages? I did search the docs but don't see this.

答案1

得分: 12

有两个概念:包名和导入路径。

包名是你在Go文件中的第一个语句中使用package声明的内容。一个目录最多只能包含一个包。

导入路径是你导入包时使用的路径,它显示了包的位置。一旦你导入了包,声明的package名称就用于限定该包中的导出标识符。

如果存在冲突的包名,你可以为其中一个定义一个别名。

import (
   "someproject/pkg/config"
   writerconfig "someproject/pkg/writer-job/config"
)

然后,config.X表示第一个包,而writerconfig.X表示第二个包。

英文:

There are two concepts: package name, and import path.

The package name is what you declare with a package as the first statement in a go file. A directory can contain at most one package.

An import path is how you import that package, and shows the location of the package. Once you import it, the declared package name is used to qualify exported identifiers from that package.

In case of conflicting package names, you define an alias for one of them.

import (
   "someproject/pkg/config"
   writerconfig "someproject/pkg/writer-job/config"
)

Then, config.X refers to the first package, and writerconfig.X refers to the second.

huangapple
  • 本文由 发表于 2021年6月23日 21:46:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/68101104.html
匿名

发表评论

匿名网友

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

确定