govisual-studio-codeauto-import

Golang in vscode: auto-import package


Imagine I want to use strconv.Atoi, but I am lazy, and want to import it automatically.

package main

import (
    "fmt"
)


func main() {
    i, _ := Atoi|("123")
    fmt.Println(i)
}

The pipe sign (|) shows where my cursor is

In PyCharm I was able to automatically import the matching function via alt+ENTER.

Is there a way that vscode changes above code to this one:

package main

import (
    "fmt"
    "strconv"
)


func main() {
    i, _ := strconv.Atoi("123")
    fmt.Println(i)
}

Solution

  • VSCode won't guess which package Atoi() is from, but if you tell it, the import will be added automatically.

    So just type

    i, _ := strconv.Atoi("123")
    

    And hit CTRL+S to save, and the import will be added automatically.

    You may also press CTRL+ALT+O which is a shortcut to Organize Imports.

    This is a reasonable compromise in Go. As part of API design, exported identifiers are created that read well with the package name. For example the constructor function that creates an MD5 hasher is md5.New() (and not for example md5.NewMD5()), the one that creates an SHA1 hasher is sha1.New(). Just entering New() it's often too verbose, and giving the package name is required to give context to what you refer to.