Help us understand the problem. What is going on with this article?

VSCodeでGo Toolsにビルドタグを渡す方法

背景

VSCodeのGo拡張を使用している際、異なるビルドタグを持ったファイルにある変数や関数等を参照しようとするとコード補完が上手く働かずundeclaredになってしまいます。これはLanguage Serverであるgopls1がタグ無しの状態で参照しているため起こる事象なのでタグを渡してあげる必要があります。

lib_util.go
// +build test

package lib

var (
    testUtil = "test util"
)
lib.go
package lib

import (
    "fmt"
)

func p() {
    fmt.Println(testUtil) // undeclared name: testUtil
}

対処法

settings.json に以下のような形で追記してやることでgoplsを含む各種Go Toolsにビルドタグを渡せます。プロジェクト毎に変更したい場合はWorkspaceレベルで設定してやると良いでしょう2

適用後はVSCodeを再起動するかF1メニューから "Developer: Reload Window" する必要があります(私の環境では "Go: Restart Language Server" だと上手くいきませんでした)。

    "go.toolsEnvVars": {
        "GOFLAGS": "-tags=test"
    },

参考文献

ryo-yamaoka
https://twitter.com/mountainhill14
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした