⭐️Go Workspaces: A Beginner's Guide

⭐️Go Workspaces: A Beginner's Guide

#90DaysOfDevOps

Day-10: Go Workspace

Go workspaces are a feature introduced in Go 1.18 that allow you to work on multiple Go modules simultaneously. Each module within a workspace is treated as a main module when resolving dependencies. This means that you can add features to one module and use them in another module without having to publish the changes to the first module.

To create a workspace, you use the go work init command. This command creates a go.work file in the root of your workspace directory. The go.work file has use and replace directives that override the individual go.mod files, so there is no need to edit each go.mod file individually.

A typical Go workspace consists of three main directories:

  • src: This directory contains the source code files of your Go projects and packages. Each project or package resides in its own subdirectory within src.

  • pkg: When you build your Go code, the resulting package objects, including compiled libraries, are stored in the pkg directory. These package objects are reused for faster subsequent builds.

  • bin: The executable binaries generated by go install or go build commands are placed in the bin directory. You can add this directory to your system's PATH to conveniently run your Go programs from anywhere.

To add modules to the workspace, you use the go work use command. This command adds the specified module directory to the workspace. You can also edit the go.work file manually.

To run a Go program in the workspace, you use the go run command. The go run command will automatically find the modules desired to run the program and download them if they are not already in the workspace.

If you are working on a project that uses a lot of Go modules, then I favor the Go workspace. They make it easy to work on multiple modules concurrently, share differences between modules, and track dependencies.

Did you find this article valuable?

Support Jatin Chourasia by becoming a sponsor. Any amount is appreciated!