Skip to content

proposal: strings/bytes: add forward and backward iterators #66206

@bGVia3VjaGVu

Description

@bGVia3VjaGVu

Proposal Details

I propose to add the function Backward to the package strings, as iterating over strings in reverse order is not trivial without allocating a new slice.

func Backward(s string) iter.Seq2[int, rune]

For now would it be:

// Returns a backwards iterator over bytes in s, yielding both the starting index and the rune.
func Backward(s string) iter.Seq2[int, rune]{
	return func(yield func(int, rune) bool) {
		for i := len(s); i > 0; {
			r, size := utf8.DecodeLastRuneInString(s[0:i])
			i -= size
			if !yield(i, r) {
				return
			}
		}
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Declined

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions