CodeGym /행동 /Go SELF /Import path vs package name

Import path vs package name

Go SELF
레벨 10, 레슨 2
사용 가능

1. Where the confusion comes from: importing one thing, writing another

When you are just starting to write Go, importing looks like simple magic: you type import "fmt" — and you can call fmt.Println. But at some point you will see import "math/rand", and in the code you will suddenly have rand.Intn(...). Or even more interesting: you will want to use both "math/rand" and "crypto/rand", and it turns out that both packages are called rand “in code”.

To stop “memorizing imports by heart” and start reading other people’s code with confidence, we need to split this into two separate entities:

  • import path — the quoted string that Go uses to find the package;
  • package name — the name you use in code as a prefix before the dot ..

Next we will look at examples from the standard library and, at the same time, slightly improve our educational console application.

2. Import path: the address Go uses to find a package

Import path is what appears in quotes in import. Important idea: import path is for the compiler and tools, not for you “for beauty”. It answers the question: “where is the source code of the package I want to connect?”

What an import path looks like

Here are typical import paths in the standard library:

  • "fmt"
  • "strconv"
  • "strings"
  • "math/rand"
  • "crypto/rand"
  • "net/http"
  • "encoding/json"

Notice: sometimes it is one word ("fmt"), and sometimes it is a path with / ("math/rand"). This does not mean “a folder on your system right now” (although historically and organizationally it is related). In your head, an import path should live as a “unique package address”.

Why this address must be unique

In Go there is an idea that one import path should unambiguously point to one semantic package. Otherwise you would not be able to understand what exactly is connected and why it works the way it does. Around this, an import compatibility rule formed: if we change a package in an incompatible way, usually we also change the import path (in modules this became even more visible).

We are not going into Go Modules, versions, and commands today — what matters to us is only the idea: import path is the dependency identifier, not “a variable name”.

Mini diagram: what Go does when it sees import

flowchart LR
    A["main.go file"] --> B["import 'math/rand'"]
    B --> C["Go finds the package by import path"]
    C --> D["The package declares its name: package rand"]
    D --> E["In code we write rand.Intn(...)"]

The key point: import path participates in locating the package, while how you refer to it in code is determined by the package name, not by the path string.

3. Package name: the name you use when writing pkg.Something

Package name is what appears in the package source file in the line package .... It is this name that becomes the prefix before the dot in your code.

For example, when you write:

fmt.Println("hi")

fmt is the package name, and Println is the exported function inside the package.

An important detail that breaks your brain once

Package name does not have to match the import path. Most often it does match the last segment of the path, which is why it seems like the same thing. But in general these are different entities:

  • import path: "math/rand"
  • package name: rand

So the string "math/rand" is not what you write to the left of the dot.

Table: the difference at a glance

Question Answered by import path Answered by package name
“Where do I find the package?” Yes No
“How do I write the prefix before .?” No Yes
“Is it a string in quotes?” Yes No (it is an identifier)
“Can it conflict with another package?” Usually no (more unique) Yes (for example, two packages can be called rand)

4. Examples from the standard library

Now let us make a few small examples (5–10 lines each) so you can train your eye: see import "..." — understand that it is an address; see something.X — understand that something is a package name (or an alias, but aliases will be covered separately).

Example: math/rand → rand

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	fmt.Println(rand.Intn(10)) // for example: 7
}

Here it is important to say out loud: we imported by path "math/rand", but in code we use the package name rand.

Example: encoding/json → json

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	b, _ := json.Marshal(map[string]int{"tasks": 3})
	fmt.Println(string(b)) // {"tasks":3}
}

We are not deeply discussing map and JSON as a topic yet (that will come later), but this example shows the main point: import path — "encoding/json", and package name — json. And it is exactly json that appears to the left of the dot.

Example: net/http → http

package main

import (
	"fmt"
	"net/http"
)

func main() {
	fmt.Println(http.MethodGet) // GET
}

Again: import path "net/http", in code http.MethodGet.

Why everything usually matches

A phrase that saves you from future panic: a lot in Go is based on conventions, and one of them is “package name usually matches the last segment of the import path”.

That is convenient for three reasons.

  • The code is easier to read: see "encoding/json" — expect json.*.
  • IDEs and tools automatically insert the needed imports.
  • People do not have to memorize extra correspondences.

But it is important to stay grounded: these are still two different mechanisms. And when you encounter code where the package name is “unexpected” (or conflicts), you should not feel like the world has broken. The world has not broken — you have just stopped living in beginner examples.

Mini problem: crypto/rand and math/rand

This is where it gets most interesting, because it is practically an ideal demonstration of “import path vs package name”.

  • "math/rand" — pseudo-random number generator (fast, convenient, but not for cryptography).
  • "crypto/rand" — cryptographically secure random bytes (slower, but suitable for keys and tokens).

And guess what the packages are called in code? Both are rand.

Let us try to import both naively:

package main

import (
	"crypto/rand"
	"math/rand"
)

func main() {}

Such code will not compile, because in one file you cannot have two packages with the same import name (and the default import name is the package name). So the import paths are different, but the package names are the same — conflict.

And this is an important idea: the conflict happens at the package name level, because that is what you use in code (rand.Something), and the compiler needs to understand unambiguously which rand you mean.

How to solve this technically — we will discuss in the next topic (that is where import aliases will appear). But conceptually you should already understand the reason: the problem is not in the paths, but in the names.

5. StudyBuddy mini-project: conscious imports

To keep the topic from remaining theory, let us continue our educational console program. Let it be called StudyBuddy: a tiny helper that asks for a name and the number of solved tasks, then prints a short report and a “motivational phrase”.

We will need the following packages:

  • fmt for input/output,
  • strconv — we already know it, but here we can do without it,
  • math/rand and time — to choose a random phrase.

Step: skeleton and clear imports

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	fmt.Println("StudyBuddy started") // StudyBuddy started
	_ = rand.Intn(10)
	_ = time.Now()
}

Notice: "math/rand" is the import path, and rand.Intn is the package name rand. The same goes for "time" → time.Now.

Step: a function that returns a phrase

We already know how to write functions, so let us do it neatly:

package main

import (
	"math/rand"
)

func pickPhrase() string {
	phrases := []string{"Hold on!", "You are doing great!", "Just a little more!"}
	return phrases[rand.Intn(len(phrases))]
}

If you have not yet covered slices ([]string) in your learning track, treat this as a “mini demo” and do not worry. You can replace it with switch and three variants, but then the example will be less lively. The main idea is still about rand.Intn: the name rand comes from the package name.

Step: time as seed so you do not get the same thing every time

package main

import (
	"math/rand"
	"time"
)

func initRandom() {
	rand.Seed(time.Now().UnixNano())
}

Yes, this already looks like “magic spells”, but it very clearly shows that you take small pieces of functionality from different packages. And each piece is connected through the import path, while used through the package name.

Step: put it together, without overload

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())

	var name string
	var solved int

	fmt.Print("Name and solved: ")
	fmt.Scan(&name, &solved)

	fmt.Printf("%s solved %d tasks. %s\n", name, solved, pickPhrase())
}

If you run it and enter:

Name and solved: Ana 5

you will get something like:

// Ana solved 5 tasks. You are doing great!

Here we have “spread” responsibility across packages. And that is normal: Go is designed so that you more often “stitch” a program together from packages than write everything from scratch.

Where import paths for your own packages come from

In the standard library, import paths are short and fixed: "fmt", "strings", "net/http". But in real projects you will see imports like "github.com/someone/project/pkg/...". This is not “fashion” and not “showing off”, but a way to make the import path unique in the world.

Historically and conceptually this is connected with the fact that the import path must unambiguously identify the package, and as the ecosystem evolved, import compatibility rules and dependency management mechanisms appeared. In discussions about modules and “package uniqueness”, the idea is stated directly: if you make incompatible changes, change the path, otherwise you break builds and people’s work.

Today it is enough to keep a simple picture in mind: for your packages, the import path starts with the “project prefix”, and the package name inside them is what is written in package ....

6. Common mistakes when working with import path and package name

Mistake #1: thinking that import "math/rand" means you should write math/rand.Intn in code.
This is a very human mistake: the brain sees a path and wants to use it as a name. But Go does not work that way: to the left of the dot there is always an identifier (package name or alias), not a string path. Therefore rand.Intn, not “the path with a slash”.

Mistake #2: confusing “what is in quotes” with “what is to the left of the dot” and trying to rename a package by changing the path string.
Sometimes a beginner thinks: “I want the package to be called random — I will just write import "math/random".” But the import path must point to a package that actually exists. If that path does not exist, the compiler is not a magician. Renaming is done by another mechanism (we will get to it), not by inventing new paths.

Mistake #3: not understanding why "crypto/rand" and "math/rand" conflict.
It seems like: “the paths are different — why is the compiler complaining?” The compiler complains because in code both packages will be called the same thing: rand. The conflict is specifically in the package name, not in the import path. Once you understand that, the problem stops being mysticism and becomes an ordinary engineering task.

Mistake #4: assuming that package name always equals the last part of the import path.
In the standard library this is almost always true, so the brain gets used to it. But this is a convention, not a law. The correct habit for reading Go code is this: import path is needed to find the package; what it is called in code is determined by the package ... inside it (or by an import alias).

Mistake #5: “why do we even need packages, can’t we just put everything in one file?”
You can — as long as the project is small. But once there is more logic, more functions, and more responsibilities, packages become a way to keep order. They do not “complicate life”; they protect you from the situation where “everything is connected to everything, and any change breaks everything”. At first, packages seem like bureaucracy. Then you write a 20-file project — and start respecting bureaucracy.

1
과제
Go SELF, 레벨 10, 레슨 2
잠금
주소와 이름
주소와 이름
1
과제
Go SELF, 레벨 10, 레슨 2
잠금
프로토콜 상수
프로토콜 상수
1
과제
Go SELF, 레벨 10, 레슨 2
잠금
서버 응답
서버 응답
1
과제
Go SELF, 레벨 10, 레슨 2
잠금
경로의 이름
경로의 이름
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION