登录
首页 >  Golang >  Go问答

io.Reader 和 fmt.Fscan 之间的无限循环

来源:stackoverflow

时间:2024-03-08 20:12:27 170浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《io.Reader 和 fmt.Fscan 之间的无限循环》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

不知道为什么,但我的 io.reader 实现似乎存在某种缺陷?

io.reader 的文档指出返回非零字节计数和非零错误应该没问题:

it may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. an instance of this general case is that a reader returning a non-zero number of bytes at the end of the input stream may return either err == eof or err == nil. the next read should return 0, eof.
callers should always process the n > 0 bytes returned before considering the error err. doing so correctly handles i/o errors that happen after reading some bytes and also both of the allowed eof behaviors.

但这对 fmt.fscan 不起作用,而是挂起程序:

package main

import (
    "fmt"
    "io"
)

type byte byte

func (b byte) read(p []byte) (n int, err error) {
    if len(p) == 0 {
        return 0, io.errshortbuffer
    }
    p[0] = byte(b)
    return 1, io.eof
}

func main() {
    var n int
    b := byte('9')
    z, err := fmt.fscan(b, &n)
    fmt.println(n, z, err)
}

当然,如果我单独使用 io.eof 返回零字节计数,它会起作用:

type Byte struct {
    v   byte
    eof bool
}

func (b *Byte) Read(p []byte) (n int, err error) {
    if len(p) == 0 {
        return 0, io.ErrShortBuffer
    }
    if b.eof {
        return 0, io.EOF
    }
    p[0] = b.v
    b.eof = true
    return 1, nil
}

func main() {
    var n int
    b := Byte{v: '9'}
    z, err := fmt.Fscan(&b, &n)
    fmt.Println(n, z, err)
}

我原来的实现中是否存在缺陷,或者我不应该依赖于 io.reader 的这一特定记录行为,并且在没有更多数据可供读取时始终单独返回 0, io.eof


正确答案


fmt.scanf 确实正确处理返回计数和 io.eof,但即使在 io.eof 之后,您的阅读器仍继续返回值。

由于扫描器实现依赖于使用 io.readfull,而后者使用 io.readatleast,因此您将需要一个更完整的实现来处理重复读取。您可以通过使用跟踪 eof 的扩展版本来测试这一点,并在第一个 read 上返回 io.eof ,它仍然可以按预期与 fmt.fscan 一起使用。

文档的主要摘录:

io.readfull

...它不会将 read 中的 eof 视为要报告的错误

io.readatleast

仅当未读取任何字节时,错误才会为 eof。

因为这些 io 帮助程序需要自己解释 io.eof ,所以它们的调用者只能查找返回的实际数据,并且由于您的阅读器继续返回数据,它们将无限期地重复调用。通过在阅读器上重复调用 io.readall 可以轻松演示这一点,每次都会返回另一个值。

b := Byte('9')
fmt.Println(io.ReadAll(b))
fmt.Println(io.ReadAll(b))
fmt.Println(io.ReadAll(b))

// [57] 
// [57] 
// [57] 

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

今天关于《io.Reader 和 fmt.Fscan 之间的无限循环》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>