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

Time:11-19

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

Is there any alternative way to do so?

CodePudding user response:

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
}

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related