VSCode报Error Loading Workspace

警告
本文最后更新于 2023-03-09,文中内容可能已过时。

当一个目录下有多个go module时,VSCode报Error loading workspace: You have opened a nested module. To work on multiple modules at once, please use a go.work file. 的错误!

image-20230103222744647

image-20230103222816322

报这个错,解决方法也提示的很清楚啦,只要按照提示就能解决!

我的目录结构:

image-20230103223320583

首先我们先看下go work命令的帮助信息:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
Golang [ main][!?][🐹 v1.19.3]
❯ go help work
Work provides access to operations on workspaces.

Note that support for workspaces is built into many other commands, not
just 'go work'.

See 'go help modules' for information about Go's module system of which
workspaces are a part.

See https://go.dev/ref/mod#workspaces for an in-depth reference on
workspaces.

See https://go.dev/doc/tutorial/workspaces for an introductory
tutorial on workspaces.

A workspace is specified by a go.work file that specifies a set of
module directories with the "use" directive. These modules are used as
root modules by the go command for builds and related operations.  A
workspace that does not specify modules to be used cannot be used to do
builds from local modules.

go.work files are line-oriented. Each line holds a single directive,
made up of a keyword followed by arguments. For example:

        go 1.18

        use ../foo/bar
        use ./baz

        replace example.com/foo v1.2.3 => example.com/bar v1.4.5

The leading keyword can be factored out of adjacent lines to create a block,
like in Go imports.

        use (
          ../foo/bar
          ./baz
        )

The use directive specifies a module to be included in the workspace's
set of main modules. The argument to the use directive is the directory
containing the module's go.mod file.

The go directive specifies the version of Go the file was written at. It
is possible there may be future changes in the semantics of workspaces
that could be controlled by this version, but for now the version
specified has no effect.

The replace directive has the same syntax as the replace directive in a
To determine whether the go command is operating in workspace mode, use
the "go env GOWORK" command. This will specify the workspace file being
used.

Usage:

        go work <command> [arguments]

The commands are:

        edit        edit go.work from tools or scripts
        init        initialize workspace file
        sync        sync workspace build list to modules
        use         add modules to workspace file

Use "go help work <command>" for more information about a command.

接下来我们初始化一个go工作空间:

1
go work init

接着把varconstmodule添加到我们的工作空间就可以了:

1
2
go work use var
go work use const

可以看到项目的一级目录下多出一个go.work文件,里面包含了我们的添加的模块。

image-20230103223923807

现在VSCode也没有报错了!

Buy Me a Coffee ~~
hiifong 支付宝支付宝
hiifong 微信微信
0%