Go package declaration, directory name, and import path relationship
Tests Go's separation of directory layout and package identity. A good answer states: import path is module path plus subdirectory; package clause is the in-code name; mismatch is legal and common for main or tests.
WHAT THIS TESTS: Whether you understand that Go separates the filesystem path used for imports from the source-level package identifier, and that the module system bridges these two worlds.
A GOOD ANSWER COVERS: A strong response explains four ideas in order. First, the import path is strictly derived from the module path declared in go.mod combined with the subdirectory path inside the module; this is how the go command locates code on disk. Second, the package clause at the top of every Go file declares the identifier used when another file qualifies an exported name, such as fmt.Println. Third, these two values are independent by design, which means a directory named server can legally contain package main, and a directory named utils can legally contain package helpers, though by convention the directory name and package name usually match. Fourth, the go tool enforces that all Go source files in a single directory must belong to the same package, with the exception of test variants like package foo_test in the same directory.
COMMON WRONG ANSWERS: Candidates often claim the directory name must match the package name, or they believe the import path is somehow generated from the package clause rather than the module plus subdirectory. Another red flag is confusing the module path with the package name, or asserting that changing the package clause renames the import path.
LIKELY FOLLOW-UPS: An interviewer might ask why package main is allowed in a directory named cmd. They might ask how internal directories restrict imports, or how package foo_test differs from package foo in the same directory. They might also probe on how go.mod sets the import path prefix for every package in the module.
ONE CONCRETE EXAMPLE: Imagine a module declared as module example.com/shop in go.mod. Inside the module there is a directory helpers/. A file in that directory starts with package utils. Another package imports it with import example.com/shop/helpers, but inside that importing file the qualified identifier is utils.ProcessOrder. The directory name helpers determines the final segment of the import path, while the package clause utils determines the name used in code. If the directory were renamed to utilities, the import path would change to example.com/shop/utilities, yet the in-code name would remain utils unless the package clause were also edited.
Read the original → go.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.