GO Packages and Modules 1 — Questions and Answers
Question 1: What file defines a Go module and its dependencies?
- package.json
- go.sum
- go.mod (Correct answer)
- Makefile
Correct answer: go.mod
`go.mod` declares the module path, Go version, and required dependencies; `go.sum` contains cryptographic hashes to verify downloads.
Question 2: What command adds a missing dependency to `go.mod`?
- go install
- go get (Correct answer)
- go add
- go fetch
Correct answer: go get
`go get <module>` downloads the module, adds it to `go.mod`, and updates `go.sum`.
Question 3: What does `go mod tidy` do?
- Formats go.mod file
- Removes unused dependencies and adds missing ones in go.mod (Correct answer)
- Updates all dependencies to latest
- Deletes the module cache
Correct answer: Removes unused dependencies and adds missing ones in go.mod
`go mod tidy` adds any missing module requirements and removes unused ones, keeping `go.mod` and `go.sum` consistent with the source code.
Question 4: What naming convention determines if a Go identifier is exported from a package?
- Prefix with `pub`
- Prefix with `export`
- Start the name with an uppercase letter (Correct answer)
- Add `//export` comment above it
Correct answer: Start the name with an uppercase letter
In Go, identifiers starting with an uppercase letter are exported (public), while lowercase identifiers are unexported (package-private).
Question 5: What is the `internal` package convention in Go?
- Packages named `internal` are compiled differently
- Code in an `internal` directory can only be imported by code in its parent tree (Correct answer)
- Internal packages are hidden from the module system
- Internal packages skip type checking
Correct answer: Code in an `internal` directory can only be imported by code in its parent tree
The `internal` directory restriction prevents external packages from importing its contents; only packages rooted at the parent of `internal` may import it.
Question 6: What does the `_` blank import (`import _ "pkg"`) do in Go?
- Imports only unexported symbols
- Prevents the package from being used
- Runs the package's `init` functions without making its symbols available (Correct answer)
- Marks the package as deprecated
Correct answer: Runs the package's `init` functions without making its symbols available
A blank import runs the package's `init()` functions (for side effects like driver registration) without making any of the package's names accessible.
What file defines a Go module and its dependencies?