How can i let this code work?

use std::io::{Cursor, Error, Write};

fn main() {
    // i want write something to memory and print it out with Write trait
    let mut buf = Vec::new();
    let mut output: Box<dyn Write> = Box::new(Cursor::new( buf));
    let result = write(&mut output);
    drop(output);
    match result {
        Ok(_) => {
            println!("Success {:?}", buf);
        }
        Err(e) => {
            println!("Failed {:?}", e);
        }
    }
}

fn write(output: &mut Box<dyn Write>) -> Result<(), Error> {
    output.write("something".as_bytes()).unwrap();
    output.flush()?;
    Ok(())
}

value borrowed here after move

Your buf value has been moved into output, so it isn't accessible through buf anymore. That said, you can do this instead:

let mut output: Box<dyn Write + '_> = Box::new(&mut buf);
6  |     let mut output: Box<dyn Write + '_> = Box::new(&mut buf);
   |                                           ---------^^^^^^^^-
   |                                           |        |
   |                                           |        borrowed value does not live long enough
   |                                           cast requires that `buf` is borrowed for `'static`

Thanks for quick reply, but it also can't work.

Actually, it does work. You just have to also add + '_ to the function.

1 Like

The following works also (Playground):

fn main() {
    let mut buf = Vec::new();
    let result = {
        let mut output: Box<dyn Write> = Box::new(&mut buf);
        write(output.as_mut())
    };
    match result {
        Ok(_) => {
            println!("Success {:?}", buf);
        }
        Err(e) => {
            println!("Failed {:?}", e);
        }
    }
}

fn write(output: &mut dyn Write) -> Result<(), Error> {
    output.write("something".as_bytes()).unwrap();
    output.flush()?;
    Ok(())
}
1 Like

Yes, it works, thanks

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.