本地开发 Local development
Definition
Every Go program is made up of packages.
You have probably noticed the package main
at the top of all the programs you have been writing.
A package named "main" has an entrypoint at the main()
function. A main
package is compiled into an executable program.
A package by any other name is a "library package". Libraries have no entry point. Libraries simply export functionality that can be used by other packages.
Naming convention
By convention, a package's name is the same as the last elemnt of its import path. For instance, the math/rand
package comprises files that begin with:
package rand
One package / Directory
A directory of Go code can have at most one package. All .go
files in a single directory must all belong to the same package. If they don't an error will be thrown by the compiler. This is true of main an library packages alike.
Modules
Go programs are organized into packages. A package is a directory of Go code that's all compiled together. Functions, types, variables, and constants defined in one source file are visible to all other source files within the same package (directory).
A repository contains one or more moudles. A module is a collection of Go packeges that are released together.
A Go repository typically contains only one module, located at the root of the repository
A file named go.mod
at the root of a project declares the module. It contians:
- The module path
- The version of the Go language your project requires
- Optionally, any external package dependenciees your project has
The module path is just the import path prefix for all packages within the module. Here's an example of a go.mod
file:
module github.com/botdotdev/exampleproject
go 1.20
require github.com/google/exampleproject v1.3.0
Each module's path not only serves as an import path prefix for the packages winthin but also indicates where to go command should took to download it.
Custom package
Questions
- What is a Go module?
- A collection of packages that are released together
- Do packages in the standard library have a module path prefix?
- Non
- What is an import path?
- A module path + pcakge subdirectory
- Do you need to put your code inside of your GOPATH?
- No, in fact you shouldn't. The entire idea of go modules is waht replaced the old go path.
- Why does Go include a remote URL in module paths?
- To simplify remote downloading of packages
- SHould you export code from the main package?
- Nope
- When should you NOT export a function, variable, or type?
- When the end-user doesn't need to know about it
- Shoudl you often change a packagge's expoerted API?
- No, try to keep changes to internal functionality
Gihtub go-lab
repository
https://github.com/xiaokatech/go-lab.git
来源
Go Programming – Golang Course with Bonus Projects(CH 12. Local development, 4:48:02): https://www.youtube.com/watch?v=un6ZyFkqFKo&t=161s