Why don't we have to use 'std' as the module prefix for packages from the standard library?

951 views
Skip to first unread message

Connor Kuehl

unread,
Sep 2, 2021, 8:18:54 PM9/2/21
to golang-nuts
I'm trying to wrap my head around modules.

When importing other packages into my project, there is a module prefix.

For example,

import (
"example.com/potato/tomato"
)

will import the "tomato" package from the "example.com/potato" module.

But this whole time as I've been learning the language, the standard
packages can be imported without any explicit prefix:

import "fmt"

and I found a go.mod in my Go distribution's standard library [1], so
that suggests to me that the standard library is implemented as a module
too.

Why don't I have to supply a prefix for the standard library packages?
Is this just a special case?

[1] https://cs.opensource.google/go/go/+/refs/tags/go1.17:src/go.mod

Volker Dobler

unread,
Sep 3, 2021, 7:10:40 AM9/3/21
to golang-nuts
On Friday, 3 September 2021 at 02:18:54 UTC+2 Connor Kuehl wrote:
But this whole time as I've been learning the language, the standard
packages can be imported without any explicit prefix:

import "fmt"

and I found a go.mod in my Go distribution's standard library [1], so
that suggests to me that the standard library is implemented as a module
too.

That assumption is a bit wrong, or at least the conclusion
drawn are not suitable. The stdlib is part of the Go installation
and not a "real" module: Modules are used to track dependencies
and select versions of dependencies. Any single Go installation
needs _exactly_ the stdlib provided by the installation and you cannot
use a "different version" of the stdlib than the one distributed in
the installation of Go itself. That's why the stdlib is not a "module"
for your projects.
But the Go installation itself needs other code and that code is
tracked as normal dependencies via modules that's why you'll
find several go.mod in the source tree of Go.

The fact that stdlib packages have short import paths predates
modules by a decade, is convenient and nothing would be gained
by typing import "golang.org/std/strings" everywhere.
It might even be misleading as you neither can replace or require
versions of this hypothetical golang.org/std module via the go.mod
file of your project.
The stdlib is not an external dependency to your code.

V.

Reply all
Reply to author
Forward
0 new messages