A Go linter that enforces immutability of struct fields and function parameters marked with special comments.
- Detects assignments to struct fields marked with
// +const
markers - Detects modifications to function parameters marked as constant
- Allows field initialization in constructor methods/functions
- Works as a standalone command or as a golangci-lint plugin
"constlint" is a static analysis tool that helps you enforce immutability in your Go code by detecting unauthorized modifications to:
- Struct fields marked with
// +const
comments - Function parameters marked with
// +const:[param1,param2,...]
directive
This linter helps prevent accidental modifications to values that should remain constant after initialization, improving code safety and predictability.
go install github.com/bunniesandbeatings/constlint/cmd/constlint@latest
To use constlint with golangci-lint as a module plugin, follow these steps:
-
Create a
.custom-gcl.yml
file in your project with the following content:version: v1.64.6 # Use your preferred golangci-lint version plugins: - module: 'github.com/bunniesandbeatings/constlint' import: 'github.com/bunniesandbeatings/constlint/plugin' version: v1.0.0 # Use the appropriate version
-
Configure golangci-lint to use the plugin by adding the following to your
.golangci.yml
file:linters-settings: custom: constlint: type: "module" description: Checks for writes to struct fields marked with // +const linters: enable: - constlint
-
Build your custom golangci-lint binary:
golangci-lint custom
-
Run your custom golangci-lint:
./custom-gcl run
-
Clone the golangci-lint repository:
git clone https://github.com/golangci/golangci-lint.git cd golangci-lint
-
Add a blank import for the constlint plugin in
cmd/golangci-lint/plugins.go
:import ( // Add other imports... // Add constlint plugin _ "github.com/bunniesandbeatings/constlint/plugin" )
-
Run
go mod tidy
and build golangci-lint:go mod tidy make build
-
Configure your
.golangci.yml
file as shown in the automatic method above. -
Run your custom golangci-lint binary.
Look in the testdata folder for examples.