前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go语言中为什么fmt.Fprintln(...)会有告警,而fmt.Println(...)却没有?

Go语言中为什么fmt.Fprintln(...)会有告警,而fmt.Println(...)却没有?

作者头像
用户1392128
发布2024-01-08 17:50:12
1450
发布2024-01-08 17:50:12
举报
文章被收录于专栏:用户1392128的专栏
问题描述:

环境:Windows10 + GoLand 2019.3.4 x64 + Golang 现象: 在使用fmt包,调用fmt.Fprintln(…)写文件时,如果不接受函数的返回值,编辑器会提示Unhandled error错误 而对于fmt.Println(…) 则不会提示

问题分析:

我们来看一下源码

代码语言:javascript
复制
// 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:

代码语言:javascript
复制
// 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源码时,却在源码中看到以下示例

代码语言:javascript
复制
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,果然是没有告警的。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-01-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题描述:
  • 问题分析:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档