Consider the following test case:
#![allow(unstable)]
trait Choose<'o> {
fn choose(a: &'o u64, b: &'o u32) -> Self;
}
impl<'o> Choose<'o> for &'o u64 {
fn choose(a: &'o u64, _b: &'o u32) -> &'o u64 { a }
}
impl<'o> Choose<'o> for &'o u32 {
fn choose(_a: &'o u64, b: &'o u32) -> &'o u32 { b }
} // '
struct Handler {
a: u64,
b: u32,
}
impl Handler {
fn new() -> Handler {
Handler { a: 14, b: 15 }
}
fn find<'a, V, W>(&'a mut self, value: W) -> Option<V> where V: Choose<'a>, W: PartialEq<V> { // '
let v = Choose::choose(&self.a, &self.b);
if value == v {
Some(v)
} else {
None
}
}
}
fn main() {
let mut h = Handler::new();
{
let v_a = h.find::<&u64, &u64>(&14u64);
println!("v_a = {:?}", v_a);
}
{
let v_b = h.find::<&u64, &u64>(&15u64);
println!("v_b = {:?}", v_b);
}
}
Suppose I have some changing state inside Handler::find, so I need &mut self. But both v_a and v_b variables pointing to Handler internals live inside their own blocks, so there is no borrow problems here. In this case a type parameter V is specified for a find method directly, and everything compiles as expected.
But then I move parameter V into Handler type signature and it stops compiling with "cannot borrow h
as mutable more than once at a time" error:
#![allow(unstable)]
trait Choose<'o> {
fn choose(a: &'o u64, b: &'o u32) -> Self;
}
impl<'o> Choose<'o> for &'o u64 {
fn choose(a: &'o u64, _b: &'o u32) -> &'o u64 { a }
}
impl<'o> Choose<'o> for &'o u32 {
fn choose(_a: &'o u64, b: &'o u32) -> &'o u32 { b }
} // '
struct Handler<V> {
a: u64,
b: u32,
}
impl<V> Handler<V> {
fn new() -> Handler<V> {
Handler { a: 14, b: 15 }
}
fn find<'a, W>(&'a mut self, value: W) -> Option<V> where V: Choose<'a>, W: PartialEq<V> { // '
let v = Choose::choose(&self.a, &self.b);
if value == v {
Some(v)
} else {
None
}
}
}
fn main() {
let mut h = Handler::<&u64>::new();
{
let v_a = h.find(&14u64);
println!("v_a = {:?}", v_a);
}
{
let v_b = h.find(&15u64);
println!("v_b = {:?}", v_b);
}
}
I really cannot understand the difference. Why mutable borrow is not released after variable v_a is dead?