I'm new to Rust and I'm working on an application that serializes some data into a byte buffer. There are several methods that take an &mut Option<&mut Buffer> and some data and return Result<usize, String>. If some buffer is given, the data is written to the buffer and the number of bytes written is returned; if None is given, the functions just return the number of bytes that would have written. See below for a simplified example.
Constructs such as &mut None and &mut Some(...) look a bit awkward to me, esp. since the Option itself is never modified (i.e. cannot be modified), just it's contents. But I understand why &Option<&mut Buffer> does not work, since it would allow multiple immutable references to the Option and therefore the contained mutable reference to the Buffer.
Is there a "better" or more idiomatic way to pass an optional, mutable Buffer reference through the code?
If I just use Option<&mut Buffer> then a call like try!(pack(buf, 1)); passes ownership of the Option to the pack method and I cannot use buf any more in foo after that.
struct S;
fn by_opt_ref(s: Option<&mut S>) {}
fn foo(r: Option<&mut S>) {
if let Some(r) = r {
by_opt_ref(Some(r));
by_opt_ref(Some(r));
let l = Some(r);
by_opt_ref(l);
// Next one will fail.
// Why the first two work then?
// by_opt_ref(Some(r));
}
}
fn main(){}