Say we need a type Cursor<T>
, which holds a mutable reference to T
. A method .dup()
duplicates the internal reference, wraps it in a new instance of Cursor<T>
and returns. Such pattern exists commonly in database driver library. Users could hold multiple cursors simultaneously, with each owning a (mutable) reference to the same connection object.
One might implements with a primitive mutable reference:
struct Cursor<'a, T> {
obj: &'a mut T,
}
impl<'a, T> Cursor<'a, T> {
fn new(t: &'a mut T) -> Cursor<'a, T> {
Cursor { obj: t }
}
fn dup(&mut self) -> Cursor<T> {
Cursor { obj: self.obj }
}
}
fn main() {
let mut i = 1;
let mut cursor_a = Cursor::new(&mut i);
let _cursor_b = cursor_a.dup();
}
Perfect and neat, and luckily Rust compiler did not complain. Fresh Rustanceans would have to work hard for shutting up the compiler, especially when fighting with references.
The invocation of ::new()
and .dup()
are on separate lines. Now what about to chain up the constructor and .dup()
? This time the compiler fails: