为 vscode 项目/终端设置 $GOPATH

set $GOPATH for a vscode project / terminals

我想为每个 vscode project/workspace 设置 $GOPATH。现在,在 .vscode/settings.json,我有:

{
    "go.gopath": "$HOME/codes/huru"
}

我关闭 vscode 并重新打开,在命令行终端,我回显 $GOPATH,它是空的。我希望 vscode 会从 "go.gopath" 读取 env 变量,但似乎不必这样做。

有人知道怎么做吗?

用户设置工作区设置上的go.gopath将替换VSCode上的GOPATH值。这个特定的 GOPATH 值是在 VSCode 上执行 Go: Current GOPATH 命令时显示的值,因此它是 而不是 $GOPATH 环境变量

go.gopath 不会替换 $GOPATH 环境变量

来自GOPATH in the VS Code Go extension的解释:

Out of the box, the extension uses the value of the environment variable GOPATH. From Go 1.8 onwards, if no such environment variable is set, then the default GOPATH as deciphered from the command go env is used.

Setting go.gopath in User settings overrides the GOPATH that was derived from the above logic. Setting go.gopath in Workspace settings overrides the one from User settings. You can set multiple folders as GOPATH in this setting. Note that they should be ; separated in Windows and : separated otherwise.

下面是我编写的示例,可能有助于理解差异。

  • 例如,我已经在本地设置了 $GOPATH env 的特定值。然后我在 用户设置 上设置 go.gopath(与 $GOPATH 相比具有不同的值)。当我执行命令 Go: Current GOPATH 时,右下角会出现一个弹出窗口,显示与我的 go.gopath 设置完全相同的值。我把 红线 放在所有这些上。
  • 但是,每当我在终端上执行 shell 命令 echo $GOPATH 时,输出仍然是我的环境变量 中的 $GOPATH 值(蓝线)。这是因为 go.gopath 设置不会替换 $GOPATH 环境变量。


在您的情况下,echo $GOPATH return 为空输出,因为您尚未设置 $GOPATH 环境变量。