safeie
August 20, 2022, 5:46am
1
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
alice
August 20, 2022, 5:55am
2
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);
safeie
August 20, 2022, 6:09am
3
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.
alice
August 20, 2022, 6:29am
4
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
system
Closed
November 18, 2022, 8:52am
7
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.