go - 忽略 "imported and not used"编译时错误

标签 go

我收到这个错误:

src/huru/utils/utils.go:6:2: imported and not used: "fmt"

src/huru/utils/utils.go:9:2: imported and not used: "net/http"

当我有这些未使用的导入时:

import (
    "fmt"
    "net/http"
)

<rant> it turns out this a rather seriously annoying "feature" because some IDEs like VSCode will automatically remove unused imports which is f*cking annoying when you are about type the characters that will use the imports but you hit save first or what not. </rant>

有没有办法用命令行选项忽略这个编译错误? 像这样的东西:

go install main --ignore-dumb-errors

最佳答案

Install additional tools

The source code for several Go tools (including goimports) is kept in the go.tools repository. To install all of them, run the go get command:

$ go get golang.org/x/tools/cmd/...

Or if you just want to install a specific command (goimports in this case):

$ go get golang.org/x/tools/cmd/goimports

To install these tools, the go get command requires that Git be installed locally.

You must also have a workspace (GOPATH) set up; see How to Write Go Code for the details.


$ goimports -help
usage: goimports [flags] [path ...]
  -cpuprofile string
        CPU profile output
  -d    display diffs instead of rewriting files
  -e    report all errors (not just the first 10 on different lines)
  -l    list files whose formatting differs from goimport's
  -local string
        put imports beginning with this string after 3rd-party packages; comma-separated list
  -memprofile string
        memory profile output
  -memrate int
        if > 0, sets runtime.MemProfileRate
  -srcdir dir
        choose imports as if source code is from dir. When operating on a single file, dir may instead be the complete file name.
  -trace string
        trace profile output
  -v    verbose logging
  -w    write result to (source) file instead of stdout
$ 

在您的源代码上运行带有标志 -wgoimports 命令。它会为你修复你的进口。这就是 Go Playground 和 IDE 修复导入的方式。


例如,

$ cat imports.go
package main

import (
    "net/http"
)

func main() {
    fmt.Println("Hello, playground")
}

$ goimports -w imports.go
$ cat imports.go
package main

import "fmt"

func main() {
    fmt.Println("Hello, playground")
}
$ 

您也可以在整个目录上运行它。

关于go - 忽略 "imported and not used"编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53576943/

相关文章:

file - 如何将文件保存在内存中——在服务器之间传输文件而不将它们存储在本地

Golang 包括本地文件

string - panic : interface conversion: interface {} is **string, 不是字符串

json - 为什么不能将此数据正确解码到我的对象模型中?

internationalization - 如何在 Go 中处理 i18n?

function - 用户定义的函数类型是否有命名约定?

go - 从 Go 中的实例打印结构定义

go - 如何从 Golang 中的 time.Now() 获取短月份名称

go - 将 64 位整数 -1 打印为十六进制的格式在 golang 和 C 之间有所不同

go - 如何获取 Go 依赖者列表