gogopath

Can I set the GOPATH using the go command line tool?


I would like to set GOPATH using the go tool upon compilation, just like adding an include path in C/++. I want the gopath to be used only within a certain project. Can this be done without setting an environment variable?


Solution

  • Instead of trying to have a GOPATH per project to separate dependencies, work with Go modules.

    A short intro on Go modules: https://ncona.com/2020/10/introduction-to-golang-modules/

    Indepth, official intro: https://blog.golang.org/using-go-modules


    My intro:

    In your repository call go init yourModuleName to start working with go modules.

    Once initialized, to me the most important command is go mod tidy. You call that and it cleans up your go.mod/go.sum files, removing what is not needed and adding what is needed.

    To add a new dependency call go get dependencyname from within your project folder to add it to your go.mod file and be able to use it in your code.

    To update a dependency, just call go get dependencyname again and it will update the version to the latest available in go.mod file.