Resolve imports and avoid cycles
Resolve imports and avoid cycles
An import declares a dependency on a package path. The default local name comes from the imported package clause, not necessarily the final path segment. An explicit alias can resolve naming conflicts. Package dependencies must be acyclic: A cannot import B if B imports A directly or through other packages.
Create the files shown below in a fresh directory, then run go run . there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples; modules are covered in detail next.
--- go.mod ---module example.test/lesson
go 1.23
--- main.go ---package main
import ( text "example.test/lesson/words" "fmt")
func main() { fmt.Println(text.Greet()) }
--- words/greet.go ---package words
func Greet() string { return "hello" }The alias text is local to main.go. The path still identifies words. Import only packages actually used in that file. Unused ordinary imports are rejected, and an alias does not create a new package.
Expected output:
helloMove shared logic to a dependency
--- go.mod ---module example.test/lesson
go 1.23
--- main.go ---package main
import ( "example.test/lesson/a" "example.test/lesson/b" "fmt")
func main() { fmt.Println(a.Label(), b.Label()) }
--- a/a.go ---package a
import "example.test/lesson/shared"
func Label() string { return shared.Prefix() + "A" }
--- b/b.go ---package b
import "example.test/lesson/shared"
func Label() string { return shared.Prefix() + "B" }
--- shared/shared.go ---package shared
func Prefix() string { return "item-" }a and b both depend on shared, which depends on neither. If a and b imported each other, Go would reject the cycle. Move genuinely shared definitions down into an independent package, or restructure the API so dependencies point in one direction. Do not create a catch-all shared package merely to hide poor boundaries.
Expected output:
item-A item-BTry it locally
Create a package calc containing Double, import it using alias numbers, and print numbers.Double(8). Use a fresh module with the same go.mod shown above; run go run .
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Packages and visibility 03: Resolve imports and avoid cycles
Check the lesson objective before moving on.
Can Go packages import each other in a cycle?
What does an import alias change?