How can I return multiple values from a for loop?

Viewed 353

I will rewrite my previous, and unclear, question. My problem is when I try to return a value from a for loop.

That's works fine:

fn main() {
    counter(5, 8);
}

fn counter(start: u32, end: u32) {
    for n in start..=end {
        println!("{}", n);
    }
}

And that doesn't work:

fn main() {
    let result = counter(5, 8);
    println!("{}", result);
}

fn counter(start: u32, end: u32) -> u32 {
    for n in start..=end {
        n
    }
}

And I try a lot of things and I can't make it work. I hope someone can help me to understand why.

1 Answers

If you declare a function like this

fn counter(start: u32, end: u32) -> u32

then you tell the compiler that it is supposed to return a single u32 value, i.e. a single unsigned integer number.

Your for loop iterates over a bunch of numbers, but it can only return one of them. You could change the return type of your function to return a Vec<u32>, a vector of u32 which is a data structure that can store a whole bunch of u32 values:

fn counter(start: u32, end: u32) -> Vec<u32> {
    (start..=end).collect()
}

Alternatively, you could also tell the compiler that the result is an iterator over u32 values:

fn counter(start: u32, end: u32) -> impl Iterator<Item = u32> {
    start..=end
}

The iterator lazily produces the values from start to end, and you can iterate over it in the calling code, e.g.

for i in counter(1, 10) {
    println!("{}", i);
}

prints the numbers from one to ten.

Related