Skip to content

proposal: cmd/go: add -go flag to go mod init #77901

Description

@sudomateo

Proposal Details

I propose adding a -go flag to the go mod init command. This flag allows users to explicitly specify the Go language version used for the go directive in go.mod rather than relying on the toolchain's default heuristic.

Background

When a user runs go mod init [module-path], the Go toolchain automatically inserts a go directive into go.mod. The version selected is typically the version of the toolchain being used, or 1.(N-n).0 after #74748 shipped in Go 1.26.0.

If a developer wants to initialize a module that targets an older version of Go for compatibility reasons (e.g., a library intended to support the last two major Go releases), they must perform a two-step process.

go mod init [module-path]
go mod edit -go=X.Y.Z

This is counter-intuitive for an initialization command, as it forces the user to initialize with a default they don't want and then immediately edit it.

Proposal

Add a -go flag to the go mod init command.

go mod init [-go=version] [module-path]

Example usage.

go mod init -go=1.25.0 example.com/example

This would produce the following go.mod regardless whether the user is running Go 1.25.X, 1.26.X, or a release candidate.

module example.com/example

go 1.25.0

Rationale

The primary motivation is user experience and consistency.

Alternatives Considered

  • Environment Variables: Users could set GOTOOLCHAIN, but this affects the entire execution environment and is overkill for simply writing a version string to a text file.

  • Do Nothing: While functional, the two-step process is a minor friction point that has been raised in community discussions (e.g., cmd/go: change go mod init default go directive back to 1.N #77653).

Compatibility

This change is fully backwards compatible. When the -go flag is omitted, the command defaults to its current behavior. The flag follows the standard -go flag syntax used elsewhere in Go.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions