youngzy
youngzy

Reputation: 407

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

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

Is there any alternative way to do so?

Upvotes: 1

Views: 264

Answers (2)

user17445174
user17445174

Reputation:

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
}

Upvotes: 3

VonC
VonC

Reputation: 1325437

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.

Upvotes: 1

Related Questions