在VSCode中使用Golang:自动导入包

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

Golang in vscode: auto-import package

问题

假设我想使用strconv.Atoi,但我很懒,想要自动导入它。

package main

import (
    "fmt"
)


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

> 管道符号(|)表示光标的位置

在PyCharm中,我可以通过alt+ENTER自动导入匹配的函数。

是否有一种方法可以将上述代码更改为以下代码:

package main

import (
    "fmt"
    "strconv"
)


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

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)
}

答案1

得分: 6

VSCode无法猜测Atoi()函数来自哪个包,但如果你告诉它,导入语句将会自动添加。

所以只需输入:

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

然后按下CTRL+S保存,导入语句将会自动添加。

你也可以按下CTRL+ALT+O,这是一个组织导入的快捷键。

这是Go语言中的一个合理折衷方案。作为API设计的一部分,创建了易于理解的与包名相匹配的导出标识符。例如,创建MD5哈希器的构造函数是md5.New()(而不是md5.NewMD5()),创建SHA1哈希器的函数是sha1.New()。仅输入New()通常太冗长,需要给出包名以提供上下文。

英文:

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 <kbd>CTRL</kbd>+<kbd>S</kbd> to save, and the import will be added automatically.

You may also press <kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>O</kbd> 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.

huangapple
  • 本文由 发表于 2022年5月25日 23:15:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/72380253.html
匿名

发表评论

匿名网友

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

确定