How do you iterate over all values produced by a function?

Tobias

I am new to go, and I have found myself writing a few for loops which look like this:

for element, err := producer.Produce(); err == nil; element, err = producer.Produce() {
    process(element)
}

where producer.Produce() is a function like reader.ReadString('\n') or fmt.Fscan(Reader, &token). I would much rather like to write

for element := range elements {
    process(element)
}

but for now, I would be satisfied to know if there is a cleaner way to iterate over the output of these kinds of functions in go. In particular, is there a nice way to get rid of this annoying duplication in the init statement and the post statement of the for statement?

Evan Shaw

I don't think there's anything quite as clean as what you're looking for. The idiomatic way to write it is:

for {
    element, err := producer.Produce()
    if err != nil {
        break
    }
    process(element)
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to iterate over all the YAML values in Golang?

How to iterate over all values() in a QMultiHash

How do you iterate over values resulting from Zip2 in Swift

How do you iterate over all cells in multi selected rows in DataGridView?

How do I iterate over a function in R?

How do you apply a function to all values in selected cells?

How do you iterate over an array that is referenced by Object?

How do you iterate over a cursor in reverse order

How do you iterate over an integer variable in Jinja?

In Java, how do you iterate over the bits of two byte arrays?

How do you iterate over an array to create a hash?

How do you iterate over this array? I know this is very basic

How do you iterate over an array of objects to create a new object?

How do you iterate over a list with a list of integers?

How to iterate over all byte values (overflowing_literals in `0..256`)

How to iterate over all values of an Enum including any nested Enums?

How to iterate over a file and put the all the id values into an list [Python]

How can I iterate over all possible values of a dictionary?

Iterate over list produced with levelsof

How do I iterate over the form values in python cgi ? Newbie

How do i iterate over the input field names and values in Angular?

Javascript - How do I iterate over values of keys in an object?

How Do You Sum a Named Function Over a Given Range of Values - Google Sheets

How to iterate over all these possibilities?

How do you iterate tuple values in a dictionary for django context

How do you append values to list then iterate through lists?

ARKit: How do you iterate all detected feature points?

How do I iterate over an array with a map function, infinitely?

Iterate over all values of a bash completion