What are Workspaces?
Workspaces allow us to work with multiple modules simultaneously without having to editgo.mod files for each module. Each module within a workspace is treated as a root module when resolving dependencies.
This is a very useful feature from Go 1.18 that simplifies development when working with multiple related modules.
Creating a Workspace
Let’s understand workspaces better by creating a practical example.Add code with an external dependency
Create a Install the dependency:
main.go file and install an example package:The Problem Workspaces Solve
What if we want to modify thestringutil module that our code depends on?
Until Go 1.18, we had to use the replace directive in the go.mod file. Now, let’s see how workspaces provide a better solution.
Using go.work
Initialize a workspace
In the This creates a
workspaces directory, create a new workspace:go.work file:Clone and modify the dependency
Download and modify the Modify
stringutil package:example/stringutil/reverse.go:Workspace Commands
go work init
Initializes a new workspace in the current directory:go work use
Adds a module to the workspace:go work sync
Synchronizes the workspace’s build list back to the modules:Use Cases
Workspaces are particularly useful when:- Developing multiple related modules simultaneously
- Testing changes across module boundaries
- Working on a dependency and the code that uses it
- Prototyping changes to external dependencies
- Avoiding the need for
replacedirectives in go.mod
The
go.work file should typically not be committed to version control, as it’s specific to your local development environment.Key Takeaways
- Workspaces were introduced in Go 1.18
- They allow working with multiple modules without editing go.mod files
- The
go.workfile defines which modules are part of the workspace - Each module in a workspace is treated as a root module
- Workspaces are ideal for local development with multiple modules
- Use
go work init,go work use, andgo work syncto manage workspaces