为什么bufio.Scanner没有提供HasNext()函数?

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

Why bufio.Scanner does not offer HasNext() func?

问题

为什么bufio.Scanner没有提供HasNext()函数?

有没有其他替代的方法可以实现这个功能?

英文:

Why bufio.Scanner does not offer HasNext() function?

Is there any alternative way to do so?

答案1

得分: 3

为什么bufio.Scanner没有HasNext方法是一个针对标准库设计者的问题。

以下是如何使用HasNext功能包装Scanner的方法:

type ScannerPlus struct {
    bufio.Scanner
    scan  bool   
    valid bool 
}

func (s *ScannerPlus) Scan() bool {
    if s.valid {
        s.valid = false
        return s.scan
    }
    return s.Scanner.Scan()
}

func (s *ScannerPlus) HasNext() bool {
    if !s.valid {
        s.valid = true
        s.scan = s.Scanner.Scan()
    }
    return s.scan
}

希望对你有帮助!

英文:

Why bufio.Scanner does not have a HasNext method is a question for the standard library designers.

Here's how to wrap a Scanner with HasNext functionality:

type ScannerPlus struct {
	bufio.Scanner
	scan  bool   
	valid bool 
}

func (s *ScannerPlus) Scan() bool {
	if s.valid {
		s.valid = false
		return s.scan
	}
	return s.Scanner.Scan()
}

func (s *ScannerPlus) HasNext() bool {
	if !s.valid {
		s.valid = true
		s.scan = s.Scanner.Scan()
	}
	return s.scan
}

答案2

得分: 1

因为bufio.Scanner只用于读取,而不用于检查是否还有更多内容。

连续调用Scan方法将逐步遍历文件的“标记”,跳过标记之间的字节。
标记的规范由类型为SplitFuncsplit函数定义;默认的分割函数将输入分割成带有行终止符的行。

因此,Scanner本身没有“下一个”的概念。分割函数有助于定义这一点,然后根据分割函数,scanner.Scan() bool可以告诉我们是否还有更多内容。

英文:

Because bufio.Scanner is only to read, not to check if there is more to read.

> Successive calls to the Scan method will step through the 'tokens' of a file, skipping the bytes between the tokens.
The specification of a token is defined by a split function of type SplitFunc; the default split function breaks the input into lines with line termination stripped

So Scanner itself has no notion of "next". A split function helps define that and then scanner.Scan() bool can tell, based on the split function, if there is more.

huangapple
  • 本文由 发表于 2021年11月18日 14:06:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/70015257.html
匿名

发表评论

匿名网友

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

确定