Vscode gives error "could not import fmt (cannot find package "fmt" )" for simple go program

huangapple go评论166阅读模式
英文:

Vscode gives error "could not import fmt (cannot find package "fmt" )" for simple go program

问题

以下是我的系统配置。

操作系统:Microsoft Windows 10 Enterprise

Go 版本:go version go1.15.7 windows/amd64

我正在尝试执行的程序如下:

package main

import "fmt"

func main() {
	fmt.Println("Hello World from Go")
}

问题是,我可以在命令行中编译和运行一个简单的 Hello World 程序,但在 vscode 中却显示错误。

could not import fmt (cannot find package "fmt" in any of 	c:\go\src\fmt (from $GOROOT)
	C:\Users\ameena\go\src\fmt (from $GOPATH))compiler

我是否漏掉了什么?

谢谢
Amit

英文:

Following is my system configuration.

OS : Microsoft Windows 10 Enterprise

Go version: go version go1.15.7 windows/amd64

The program which I am trying to execute is as below

package main

import "fmt"

func main() {
	fmt.Println("Hello World from Go")
}

The problem is I can compile and run a simple Hello world program from the command line but inside vscode it showed the error.

could not import fmt (cannot find package "fmt" in any of 	c:\go\src\fmt (from $GOROOT)
	C:\Users\ameena\go\src\fmt (from $GOPATH))compiler

Am I missing here something ??

Regards
Amit

答案1

得分: 2

根据这里的解释(适用于GoLand,但也适用于VSCode-Go):

  • GOROOT是一个变量,用于定义Go SDK的位置。除非你打算使用不同的Go版本,否则不需要更改此变量。
  • GOPATH是一个变量,用于定义工作区的根目录。默认情况下,工作区目录是用户主目录中名为go的目录(对于Linux和MacOS是~/go,对于Windows是%USERPROFILE%/go)。

如果你没有在默认路径(C:\Go)中安装Go,则需要将GOROOT环境变量设置为Go安装的根文件夹。

OP Amit Meena评论中确认:

在我的环境中,GOROOT变量缺失:创建GOROOT变量并将其指向Go安装目录后,VSCode中的错误消失了。

英文:

As explained here (for GoLand, but it applies to VSCode-Go as well)

> GOROOT is a variable that defines where your Go SDK is located.
You do not need to change this variable, unless you plan to use different Go versions.
>
> GOPATH is a variable that defines the root of your workspace.
By default, the workspace directory is a directory that is named go within your user home directory (~/go for Linux and MacOS, %USERPROFILE%/go for Windows).

If you did not install Go in the default paths (C:\Go), you need to set the GOROOT environment variable to the root folder of your Go installation.

The OP Amit Meena confirms in the comments:

> Seems in my env GOROOT variable was missing: on creating the GOROOT variable and pointing it to go installation directory, the error has gone from VSCode.

huangapple
  • 本文由 发表于 2021年11月12日 15:29:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/69939306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定