GO Packages and Modules 2 — Questions and Answers
Question 1: What is the purpose of `init()` functions in Go?
- They are the program's entry point
- They run automatically before `main`, used for package-level initialization (Correct answer)
- They initialize struct fields
- They replace constructors in OOP
Correct answer: They run automatically before `main`, used for package-level initialization
`init()` functions run automatically after variable initialization when the package is first imported, and a package can have multiple `init` functions.
Question 2: What happens if a Go source file imports a package but does not use it?
- A warning is emitted
- The unused import is ignored
- The program compiles with reduced performance
- A compile error occurs (Correct answer)
Correct answer: A compile error occurs
Go enforces that every imported package must be used; an unused import causes a compile-time error, keeping codebases clean.
Question 3: How do you specify a major version upgrade (v2+) in a Go module import path?
- go get -major
- Append `/v2` (or higher) to the module path (Correct answer)
- Use replace directive in go.mod
- Set GOVERSION=2 environment variable
Correct answer: Append `/v2` (or higher) to the module path
Go module semantic versioning requires appending `/v2`, `/v3`, etc. to the module path for major versions ≥2, e.g., `github.com/pkg/errors/v2`.
Question 4: What is the Go module proxy and why is it used?
- A local cache of compiled binaries
- A server that caches module downloads for faster and more reliable fetching (Correct answer)
- A reverse proxy for Go HTTP servers
- A tool for proxying network requests in tests
Correct answer: A server that caches module downloads for faster and more reliable fetching
The Go module proxy (default: `proxy.golang.org`) caches module source code, improving download speed, reliability, and availability of older versions.
Question 5: What is a package alias in Go and how is it declared?
- A package declared with `type`
- A short name for an imported package: `import alias "path/to/pkg"` (Correct answer)
- A copy of a package's exported symbols
- A deprecated feature removed in Go 1.18
Correct answer: A short name for an imported package: `import alias "path/to/pkg"`
Package aliases (`import f "fmt"`) give an imported package a different local name, resolving conflicts or providing a shorter reference.
Question 6: What does `GOPATH` represent in older Go tooling?
- The path to the Go compiler
- The workspace directory containing src, pkg, and bin for pre-module Go development (Correct answer)
- The directory where go.mod files are stored
- The path to Go standard library sources
Correct answer: The workspace directory containing src, pkg, and bin for pre-module Go development
Before Go modules, `GOPATH` defined the workspace with `src` (source), `pkg` (compiled packages), and `bin` (executables) directories.
What is the purpose of `init()` functions in Go?