首页 Go配置
文章
取消

Go配置

前言

网上诸多教程确实有一定的参考价值,但是在参考这些内容之时要注意是否过时,有条件尽可能去官网看英文原版,可以少走很多弯路;

问题汇总

路径问题(VS Code)

1. 提示gopls无法在工作区找到模块

报错具体内容: gopls was not able to find modules in your workspace.

When outside of GOPATH, gopls needs to know which modules you are working on.
You can fix this by opening your workspace to a folder inside a Go module, or by using a go.work file to specify multiple modules.
See the documentation for more information on setting up your workspace: https://github.com/golang/tools/blob/master/gopls/doc/workspace.md.

我首次遇见该问题表现出来的行为是代码可以正常运行,但是VS Code的报错提示一直存在,强迫症不能忍;

后面的某一天,我知道了之所以可以正常运行是因为这个提示涉及到工作区目录的初始化与规范化,用于规范管理Go代码,而不涉及到错误。

解决方案:
先看原文怎么说的:

Starting with Go 1.18, the go command has native support for multi-module workspaces, via go.work files. These files are recognized by gopls starting with gopls@v0.8.0.
The easiest way to work on multiple modules in Go 1.18 and later is therefore to create a go.work file containing the modules you wish to work on, and set your workspace root to the directory containing the go.work file.

也就是说需要建立一份go.work文件以便于包含我们所需要的模块,而该文件一般建于我们工作区下的根目录;

此时就需要在该目录下进行初始化,使用init命令;

1
go work init < Your Path >

最好指定目录信息,不然go.work中的use字段不会填充。

最终这个问题就得到了解决。

本文由作者按照 CC BY 4.0 进行授权

CPP总结&经验

Q K V的理解