relationship between directory structure and packages in golang

Viewed 535

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 Answers

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.

Related