Go语言是否有用于io.Readers的格式说明符?

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

Does Go have a format specifier for io.Readers?

问题

我想要的是这样的东西:

r := strings.NewReader("fee fi fo fum")
fmt.Printf("%r\n", r)

其中 %r 是一个格式说明符,用于从 io.Reader 中读取。我在 fmt 的文档 https://pkg.go.dev/fmt 中没有看到类似的内容,但有可能我错过了。

英文:

What I want is something like this:

r := strings.NewReader("fee fi fo fum")
fmt.Printf("%r\n", r)

where the %r would be a format specifier that reads from an io.Reader. I didn't see anything like that in the fmt documentation https://pkg.go.dev/fmt, but it's possible I missed it.

答案1

得分: 2

io.Reader可以是一个永远不会结束的流,因此fmt.Printf的渲染可能永远不会完成。

如果你知道会有一个离散的有效负载,并且它不是过大的话,你可以将内容加载到内存中:

r := strings.NewReader("fee fi fo fum")
b, _ := io.ReadAll(r)
fmt.Printf("%q\n", b)

这将把读取器的当前位置移动到末尾,因此如果你需要在将来的调用中“重放”读取器,你需要使用另一个io.Reader(例如bytes.Buffer)来保存原始内容:

r := strings.NewReader("fee fi fo fum")

if debug {
    var b bytes.Buffer
    _, err = io.Copy(&b, r) // 处理错误

    log.Printf("io.Reader内容:%q\n", b.String())

    r = &b // 重放
}

// 保留r io.Reader的内容和位置

链接:https://go.dev/play/p/JRS34uX1R1G

英文:

An io.Reader may be a stream which never ends, as such a fmt.Printf rendering may never complete.

If you know there will be a discrete payload and it's not excessively large, you can load the contents to memory:

r := strings.NewReader("fee fi fo fum")
b, _ := io.ReadAll(r)
fmt.Printf("%q\n", b)

https://go.dev/play/p/DZybA_f6Ole

This will however move the reader current position to the end, so if you need to "replay" the reader in future calls, you need to use another io.Reader (e.g. bytes.Buffer) to hold the original content:

r := strings.NewReader("fee fi fo fum")

if debug {
	var b bytes.Buffer
	_, err = io.Copy(&b, r) // handle err

	log.Printf("io.Reader content: %q\n", b.String())

	r = &b // replay
}

// r io.Reader content and position preserved

https://go.dev/play/p/JRS34uX1R1G

huangapple
  • 本文由 发表于 2022年2月8日 02:09:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/71023356.html
匿名

发表评论

匿名网友

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

确定