Can someone explain why GOPATH is convenient and how it should be used in general?

前端 未结 3 366
[愿得一人]
[愿得一人] 2020-12-05 03:49

I am new to Go programming language and every tutorial starts off from setting GOPATH to current project folder.

Am I missing something? Is programmer really suppos

3条回答
  •  [愿得一人]
    2020-12-05 04:32

    The goal of the GOPATH is to centralize all packages into one common workspace. It is not really a new concept by itself (think of the Java Classpath for example), but Go's use is drastically simpler by not supporting packages versioning.

    The Go programmer isn't supposed to set GOPATH manually when entering a new project folder. Each project folder is supposed to be a package by itself, and reside in the GOPATH along other packages, so GOPATH should be set only once. Tutorials begin by setting the GOPATH in order to isolate the tutorial workspace from anything else (or simply assuming that a user hasn't set the GOPATH, yet).

    GOROOT is set to provide the standard packages to the Go programmer, you don't need to do anything with it. In short, there is a single rule for GOROOT: never, ever, touch it. Don't install anything in it, don't modify standard packages, etc.

    I'm not aware of a tool to detect Go projects in the current directory, but it shouldn't be highly complex to create.

    How you handle different projects is up to you. The Go way is to put every project as a package in the $GOPATH/src directory and do everything from there. As I don't really like it, I defined my GOPATH to be $HOME/.go. Then I put each project in a dedicated directory somewhere else (anywhere in my computer), and symlink the project directory into my $GOPATH/src dir. I can then use every Go toolchain command (e.g. go build myproject), use the project as package for another one, etc.

提交回复
热议问题