Unexpected output in async program

⚓ Rust    📅 2026-01-25    👤 surdeus    👁️ 1      

surdeus

I've this simple MWE which isn't outputting what I expect:

use futures::{StreamExt, stream::iter};

#[tokio::main]
async fn main() {
    #[derive(Debug)]
    struct TrivialStats {
        count: i32,
    }
    let mut stats = TrivialStats { count: 0 };
    // let mut stats = Box::new(stats);  // Adding this line makes it not compile (as expected)

    // fn check_copy<T: Copy>(_t: T) {}
    // check_copy(stats);  // Does not compile because TrivialStats is not Copy

    iter(0..100)
        .map(|_item| {
            async move {
                stats.count += 1;
            }
        })
        .buffer_unordered(10)
        .collect::<Vec<_>>()
        .await;

    println!("Final stats: {:?}", stats);
}

It prints: ... { count: 0 } but I would expect it to print 100 or error that I'm not handling the mut refs properly. The compiler does provide a warning that:

value captured by `stats.count` is never read
did you mean to capture by reference instead?

However, changing stats to be Box<TrivialStats> makes the compiler error saying it can't copy:

main.rs(10, 21): move occurs because `stats` has type `Box<TrivialStats>`, which does not implement the `Copy` trait

However, TrivialStats is also not copy as can be verified by un-commenting the test above. Am I missing something obvious?

11 posts - 4 participants

Read full topic

🏷️ Rust_feed