Could not import fmt.(or any other basic libs) VS Code Go Extension

Viewed 5715

I recently installed go and the vscode go extension on my machine running Ubuntu 20.04. Everything works fine but there's one bug I cannot solve. When I create a new .go file I get the following error. However when I save the file, restart vscode, the error goes away and everything is fine.

enter image description here

The code I'm writing is a basic hello world program. Even when the error is there and I run go run or go build everything works fine. Its just an annoyance when creating a new file.

package main

import "fmt"

func foo() {
    fmt.Println("Hello world!")
}

If I run echo $GOPATH or echo $GOROOT in the terminal they both blank. Additionally when I run the go env command they defined as follow: GOROOT="/usr/local/go" and GOPATH="/home/chadley/go" (chadley being username)

I have changed nothing in the extension settings or any other environment variables.

1 Answers

The comment provided by @xarantolus solved the issue. Thanks a lot.

Did you create a Go module in the root of your VScode workspace? The extension sometimes seems to have problems when no module is defined, so the question is if the error goes away after running something like go mod init your.import/path?

This page also proved helpful for go modules

Related