Go語言中爲什麼fmt.Fprintln(...)會有告警,而fmt.Println(...)卻沒有?

問題描述:

環境: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.
func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
	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.
func Println(a ...interface{}) (n int, err error) {
	return Fprintln(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.
func Printf(format string, a ...interface{}) (n int, err error) {
	return Fprintf(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.
func Printf2(format string, a ...interface{}) (n int, err error) {
	return Fprintf(os.Stdout, format, a...)
}

但是,同樣的告警還是出現在了Printf2函數上
在這裏插入圖片描述
然而,我在深入研究fmt源碼時,卻在源碼中看到以下示例

func ExampleFprintf() {
	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,果然是沒有告警的。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章