Johntopia
Johntopia

Reputation: 353

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

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

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

Upvotes: 21

Views: 40660

Answers (6)

Updating Go Tools in VSCODE solved my problem.

Upvotes: 1

Morani
Morani

Reputation: 498

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.

Upvotes: 1

Anti Mafia
Anti Mafia

Reputation: 331

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

enter image description here

Upvotes: 3

Spandan Joshi
Spandan Joshi

Reputation: 902

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 :).

Upvotes: 11

Muhammad Tariq
Muhammad Tariq

Reputation: 4644

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.

Upvotes: 13

Johntopia
Johntopia

Reputation: 353

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!

Upvotes: 0

Related Questions