Why does VS Code not auto-import packages using Go?

Viewed 17458

Hi I am new to Go and currently use VS Code as IDE.

I am totally new to back-end development and I am trying to use Go for the job.

While I was teaching myself via Youtube, I faced a problem.

The problem is that the VS Code does not auto-import any package made by me.

I don't know why but I did get some clues about it.

My Guess

  • My editor does not recognize the location of the package

also my projects are located at C:\Users\John\Desktop\GoProjects while the gopath=C:\Users\John\go and the goroot=c:\go

Can anyone give me a solution to this?

main.go myapp/app.go

5 Answers

In my case disabling gopls worked and easily solved the issue.

File -> Preferences -> Settings -> Use Language Server (Type in search box and uncheck it)

Read the complete thread here for detailed information : https://github.com/microsoft/vscode-go/issues/2473

You can also import missing libraries using Command Palette (Cntrl + Shift + P) which is also very simple.

Open the Command Palette and run the command Go: Add Import to get a list of packages that can be imported to your Go file. Choose one and it will get added in the import block of your Go file.

There is no issue in my GOPATH or GOROOT but auto import not working in my case & there is some squiggly alert in my code. I fix this by following these simple 3 steps.

  1. CTRL + SHIFT + P then type go tool

enter image description here

  1. Select install/Update Tools then select all checkbox

enter image description here

  1. Click ok & download all packages. Now close & reopen vs code it will remove all squiggly lines & auto-import packages

I did the same thing. now everything works perfectly :).

Just check Go: Autocomplete Unimported Packages in File > Preferences > Settings It worked for me

enter image description here

Solved. It's not a 100% perfect one though.

I don't know why Go is so inconvenient about this but here's my solution.

  1. set GOPATH to my working directory, in this case C:/Users/John/GoProjects

This part is important because this is where the path, your editor begins your relative path

  1. Create three directories; bin, pkg, src

  2. Ctrl + Shift + P => goinstall Install/Update tools

  3. In the main.go file, import the package manually.

enter image description here

I hope this could help people facing the same problem! Happy coding!

You should have go.mod file for autoimporting. Just run go mod init example.com/test-app then go mod tidy and autoimporting will work fine.

Related