问题描述:
环境:Windows10 + GoLand 2019.3.4 x64 + Golang
现象:
在使用fmt包,调用fmt.Fprintln(…)写文件时,如果不接受函数的返回值,编辑器会提示Unhandled error错误
而对于fmt.Println(…) 则不会提示
问题分析:
我们来看一下源码
// Fprintln formats using the default formats for its operands and writes to w.// Spaces are always added between operands and a newline is appended.// It returns the number of bytes written and any write error encountered.funcFprintln(w io.Writer, a...interface{})(nint, errerror){
p:=newPrinter()
p.doPrintln(a)
n, err= w.Write(p.buf)
p.free()return}// Println formats using the default formats for its operands and writes to standard output.// Spaces are always added between operands and a newline is appended.// It returns the number of bytes written and any write error encountered.funcPrintln(a...interface{})(nint, errerror){returnFprintln(os.Stdout, a...)}
两个函数均有两个返回值 :n int, err error
那么为什么会出现上面奇怪的现象呢?为了搞清这个问题,我在flag/print.go中添加了一个同样的函数,区别只是换了个名字Printf2:
// Printf formats according to a format specifier and writes to standard output.// It returns the number of bytes written and any write error encountered.funcPrintf(formatstring, a...interface{})(nint, errerror){returnFprintf(os.Stdout, format, a...)}// Printf formats according to a format specifier and writes to standard output.// It returns the number of bytes written and any write error encountered.funcPrintf2(formatstring, a...interface{})(nint, errerror){returnFprintf(os.Stdout, format, a...)}
但是,同样的告警还是出现在了Printf2函数上
然而,我在深入研究fmt源码时,却在源码中看到以下示例
funcExampleFprintf(){const name, age="Kim",22
n, err:= fmt.Fprintf(os.Stdout,"%s is %d years old.\n", name, age)// The n and err return values from Fprintf are// those returned by the underlying io.Writer.if err!=nil{
fmt.Fprintf(os.Stderr,"Fprintf: %v\n", err)}
fmt.Printf("%d bytes written.\n", n)// Output:// Kim is 22 years old.// 21 bytes written.}
而fmt.Fprintf(os.Stderr, “Fprintf: %v\n”, err)没有接受返回的错误,却没有告警
事情变得越来越有意思了
我把这段代码复制出来,放到自己的代码中,神奇的事情又发生了
百思不得其解,然后查看告警提示
这么操作一次后,发现告警消失了,但是这肯定不是终点啊,知其然也要知其所以然。
不甘心的我又操作了一次,添加了个Printf3函数,然后就发现了这个
那么,问题就清晰了,这个告警是编辑器的代码检测告警,规则也是在Golang里定义的,按照这个思路在Golang的Probable Bugs中添加Exclude规则就可以解决这个问题了。
为了验证我的想法,我把编辑器切换成VS Code,果然是没有告警的。