为什么 “go vet” 在这里没有显示错误?

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

Why does "go vet" not show an error here?

问题

使用以下代码,go vet没有显示我期望的“越界”错误:

package main

func main() {
    a := make([]string, 1)
    a[2] = "foo"
}

根据go vet文档

标志:-shift

移位操作的长度等于或超过变量的长度。

如果go vet不是用于捕获这些错误的工具,那么什么工具可以呢?编译和/或测试代码可以捕获这个错误,但我正在寻找一种基于静态分析的工具。

英文:

With the following code, go vet does not show an "out of bounds" error as I would expect:

package main

func main() {
	a := make([]string, 1)
	a[2] = "foo"
}

From the go vet documentation:

> Flag: -shift
>
> Shifts equal to or longer than the variable's length.

If go vet is not the tool to catch these errors, what is? Compiling and/or testing the code will catch this, but I'm looking for a static analysis based tool.

答案1

得分: 4

Go vet是用于捕捉可疑运行时错误的工具,它使用一些启发式方法。第一段对其工作原理进行了详细说明。

Vet会检查Go源代码并报告可疑的结构,例如Printf调用的参数与格式字符串不匹配。Vet使用的启发式方法不能保证所有报告都是真正的问题,但它可以找到编译器未能捕捉到的错误。

文档中还提到:

请注意,该工具不会检查每个可能的问题,而是依赖于不可靠的启发式方法。

此外,你使用的代码用于检查包的合规性,对于这些启发式方法来说非常难以找到,因为你使用了可以在运行时追加或修改的动态切片。因此,很难想象出一个完美的启发式方法来解决这个问题。

fmt.Printf("%d", "scsa", "DSD")

这些启发式方法可以捕捉到像这样的错误,这完全取决于训练数据是什么。

因此,Go vet应该是一个快速检查是否有一些常见错误被忽略的工具(如果它能被捕捉到的话),它不像编译工具或运行时检查器,它只是对你编写的代码运行一些启发式方法。

文档还提供了一份可用检查项的列表,其中包括:

汇编声明、复制锁、Printf系列、方法、结构标签等等,你可以查看并阅读完整的文档。

英文:

Its true that Go vet is for catching suspicious runtime error, by using some heuristics. The first Para is exact regarding its work

> Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string. Vet uses heuristics that do not guarantee all reports are genuine problems, but it can find errors not caught by the compilers.

also in documentation its mentioned that

> Note that the tool does not check every possible problem and depends on unreliable heuristics.

also the code which you are using to check for vetting your package is something very difficult to find by those heuristics as you are using a dynamic slice which can be appended or modified at runtime.
thereby not a perfect heuristic can be thought about for that.

fmt.Printf("%d", "scsa", "DSD")

those heuristic can catch things like this it all depends on what the training data is.

So vet should be a tool to take a quick look whether there is some general mistake which has been missed by you (If It gets caught 为什么 “go vet” 在这里没有显示错误? )its nothing like a compile tool or runtime checker it just runs some heuristics on the plane code you have written.

also documentation provides a list of available checks some examples are

> Assembly declarations,
> Copying locks,
> Printf family,
> Methods,
> Struct tags,

etc there are many, you can see and read the complete documentation

huangapple
  • 本文由 发表于 2016年12月8日 15:23:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/41033940.html
匿名

发表评论

匿名网友

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

确定