Qualified identifiers
September 15, 2023
One of the features of Go I found most discomforting when I started using the language, was that of qualifiers. Depending on which previous languages you may have experience with, you may find them perfectly natural, or entirely strange. Let’s see what they are…
Qualified identifiers
A qualified identifier is an identifier qualified with a package name prefix. Both the package name and the identifier must not be blank.
QualifiedIdent = PackageName "." identifier .
A qualified identifier accesses an identifier in a different package, which must be imported. The identifier must be exported and declared in the package block of that package.
math.Sin // denotes the Sin function in package math
Let’s illustrate with a complete (but trivial) example. Suppose we have a package foo
:
package foo
const Foo = "the fooiest"
Now to the exported symbol Foo
from another package, we need to both import the foo
package, and use a qualified identifier:
package main
import "foo"
var x = foo.Foo
By way of comparison, this the rough equivalent of the following in JavaScript, which doesn’t use qualifiers.
import { foo } from "foo";
var x = foo;
As an aside, you can avoid the use of qualified identifiers in Go by using “dot imports”, but it’s generally frowned upon (and I honestly wish this wasn’t possible). Please don’t do this, but here’s what it would look like:
package main
import . "foo"
var x = Foo
Quotes from The Go Programming Language Specification Version of August 2, 2023