In the previous articles, we had to download and use many third-party libraries. In today's article, we will discuss how to delete Golang packages when they are no longer used.
Method 1: Delete the source directory
If you want to remove the installed packages, just delete the source directory and package files.
The GOPATH
 environment variable lists places to look for Go code. On Unix, the value is a colon-separated string. On Windows, the value is a semicolon-separated string.Â
GOPATH
 must be set to get, build and install packages outside the standard Go tree.
$GOPATH is the location for packages we create and third-party packages that we may have imported. When you want to delete a package, find the package file under $GOPATH/pkg/<architecture>
and the source directory under $GOPATH/src
, for instance: $GOPATH/pkg/windows_amd64
You can find your GOPATH environment variable by running the below command on Windows:
echo %GOPATH%
Output:
On Linux
echo $GOPATH
Alternatively you can also use below command:
go env GOPATH
Method 2: Using the go command
go clean command
With the go clean -i
flag, you can remove the archive files and executable binaries that go install (or go get) creates for a package. Both of these are often found under $GOPATH/pkg
and $GOPATH/bin
.
Clean removes object files from package source directories. The go command builds most objects in a temporary directory, so go clean is mainly concerned with object files left by other tools or by manual invocations of go build.
If a package includes an executable, go clean -i
will only remove that and not archive files for sub packages, like gore/gocode in the example below, so be sure to include ... to the import path. The source code then needs to be removed manually from $GOPATH/src
.
Here is an example of using the go clean command to remove packages from your computer. The -r
flag causes clean to be applied recursively to all the
dependencies of the packages named by the import paths.
go get command
You can use the following command to remove your unused packages:
go get package@none
Here @none is the version part set as none. Thus the system will remove the package.
go get github.com/motemen/gore@none
Summary
We can immediately delete the files and folders associated with the installed package if you wish to uninstall any packages. The source directory under $GOPATH/src
and the generated package file under $GOPATH/pkg/<architecture>
must both be deleted. Another way to delete the installed packages is by using the go clean
or go get package@none
command.
References
https://pkg.go.dev/cmd/go#hdr-GOPATH_environment_variable
https://pkg.go.dev/cmd/go/internal/clean
Removing packages installed with go get - Stack Overflow