𝗣𝗮𝗰𝗸𝗮𝗴𝗲.𝗷𝘀𝗼𝗻 𝘃𝘀 𝗚𝗼.𝗺𝗼𝗱: 𝗪𝗵𝗲𝗿𝗲 𝗗𝗶𝗱 𝘁𝗵𝗲 𝗩𝗲𝗿𝘀𝗶𝗼𝗻 𝗙𝗶𝗲𝗹𝗱 𝗚𝗼?
If you move from JavaScript to Go, one thing will surprise you.
In a package.json file, the version is right at the top. You can read it. You can change it in a pull request. You can search for it. It is a fact that lives inside your code.
Now open a go.mod file. The version is not there.
This is not a mistake. It is a choice.
Go does not use a version field for your own module. Instead, Go uses git tags.
To set a version in Go, you do this:
- git tag v1.2.3
- git push origin v1.2.3
The git tag is the single source of truth. When someone runs go get, Go looks at your repository tags to find the right commit.
This design has a major strength. A version can never point to the wrong code. In npm, the published code and the tagged source can drift apart. In Go, they are the same thing because the version is a pointer to a commit.
However, this changes your workflow in several ways:
- Finding your version requires a command. You must run git describe --tags instead of looking at a file.
- Version bumps do not show up in code reviews. A tag push is not a code change, so it does not appear in a pull request.
- Local builds use pseudo-versions. Until you tag a commit, you see a long string of numbers and hashes instead of a clean version like v1.2.3.
- Major versions change your import path. In npm, you change the version number but keep the package name. In Go, v2 and above require a path change like /v2. This allows a program to use v1 and v2 of the same library at the same time without clashes.
Most other ecosystems keep the version in a file:
- Node: package.json
- Rust: Cargo.toml
- Python: pyproject.toml
- Java: pom.xml
- .NET: .csproj
Go is different. It relies on git tags only.
If you want your Go binary to show a clean version, you can inject it during the build process using ldflags. Many developers also use tools like goreleaser to automate the tag and release process.
The two models represent different priorities:
- File-based versions are easy to read and review. The risk is that the file can drift from the actual code.
- Tag-based versions are impossible to fake. The cost is that they are harder to see and manage.
Go chose the tag model to ensure the manifest always matches the code.
Goのコードをリリースしている方へ:日常の業務において、タグのみのモデル(tag-only model)はどのように感じられますか?それについて、何か変更したい点はありますか?
出典: https://dev.to/dalirnet/packagejson-vs-gomod-where-did-the-version-field-go-3301