rust - How can I force a value to be moved from an inner scope to an outer instead of borrowing? -
i'm newbie in rust. how can force value moved inner scope outer instead of borrowing?
let mut r_buf = bufreader::new(file.unwrap()); let mut eof = false; while !eof { let piece = r_buf.fill_buf(); if piece.is_ok() { let mut piece = piece.unwrap(); let piece_len = piece.len(); if opt.compress { let deflated = deflate_bytes(piece); if deflated.is_none() { panic!(format!("cant deflate file {}", path.to_str().unwrap_or(""))); } let deflate_unwrapped = deflated.unwrap(); let deflate_deref = deflate_unwrapped.deref(); piece = deflate_deref; } /* bf: &mut bufstream<file>*/ let w = bf.write(piece); if w.is_ok() { written_bytes = w.unwrap(); } i can't move &[u8] deflate_deref piece. i've tried vec<u8> , box<&[u8]>. have error "deflate_unwrapped not live long enough"... can't operate [u8] type because doesn't have exact size in compile type, while references can borrow...
in case must use specific or rewrite code?
playground link http://is.gd/u8wfm7
let’s reduce code minimal example:
fn main() { let = { let b = 42; &b }; } for case boiling down to: trying take reference , storing reference after original object has passed out of scope.
there 2 main ways of dealing this:
change scope of variable taking reference to:
fn main() { let b; let = { b = 42; &b }; }so long not dealing crossing function boundaries (that is, returning reference inside function) or combinations loop boundaries, typically best solution.
don’t take reference, rather processing wish @ time:
fn main() { let = { let b = 42; b.clone() }; }in particular case, turning
&[u8]vec<u8>, can writtenvec::from(slice). of course, in specific example still need worry storing vector somewhere in first way, or else usingcow<[u8]>whole thing.
there article have written among other things considers these questions might find helpful: http://chrismorgan.info/blog/rust-fizzbuzz.html. deals string , str dealing more vec<u8>/bytes , [u8], concepts same.
Comments
Post a Comment