Weird behaviour of impl Write for Cursor<[u8; N]>

⚓ Rust    📅 2025-09-04    👤 surdeus    👁️ 3      

surdeus

Hello y'all

I've been writing some test code and encountered this gem:
link to playground

use std::io::Write;
fn main() {
    let buff = [0u8; 1024];
    let mut crs = std::io::Cursor::new(buff);
    
    let _ = write!(&mut crs, "Hello there");
    let _ = crs.flush();
    
    let mut buff2 = [0u8; 1024];
    let mut crs2 = std::io::Cursor::new(&mut buff2[..]);
    
    let _ = write!(&mut crs2, "Hello there");
    let _ = crs2.flush();
    
    println!("Result: {} :<", String::from_utf8_lossy(&buff));
// Result:  :<
    println!("Expected: {} :)", String::from_utf8_lossy(&buff2));
// Expected: Hello there :)
}

Would you agree this behaviour is unexpected?
Does Cursor::new(buff) crate a copy of that buffer internally?
If not why doesn't rustc complain the buff was moved when used again in println!?

3 posts - 3 participants

Read full topic

🏷️ Rust_feed