Skip to content

proposal: bufio: Scanner.{Text,Bytes}Seq #70657

Closed as not planned
Closed as not planned
@pkierski

Description

@pkierski

Proposal Details

Once iterators are introduced in 1.23 there is growing number of libraries based on this feature. Reading data by lines or words are quite common task and could be accomplished with for ... range loop. It requires just two simple methods for bufio.Scanner:

func (s *Scanner) TextSeq() iter.Seq[string] {
	return func(yield func(string) bool) {
		for s.Scan() {
			if !yield(s.Text()) {
				break
			}
		}
	}
}

func (s *Scanner) BytesSeq() iter.Seq[[]byte] {
	return func(yield func([]byte) bool) {
		for s.Scan() {
			if !yield(s.Bytes()) {
				break
			}
		}
	}
}

Reading whole file as collection of lines could be like:

	f, err := os.Open("file.txt")
	if err != nil {
		panic(err)
	}
	defer f.Close()
	scanner := bufio.NewScanner(f)
	
	// read all lines as slice of strings
	lines := slices.Collect(scanner.TextSeq())

	// instead of:
	// lines := make([]string, 0)
	// for scanner.Scan() {
	// 	lines = append(lines, scanner.Text())
	// }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Declined

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions