I've got a type T
as well as a function blackbox(&mut [T]) > Option<&mut T>
and want to write a function f(x: &mut [T]) > Result<&mut T, &mut [T]>
that tries to
apply blackbox
to x
, and if it "fails" returns Err(x)
like this:
fn f(x: &mut [T]) > Result<&mut T, &mut [T]> {
if let Some(x) = blackbox(x) {
return Ok(x);
}
Err(x)
}
But now the compiler complains about *x
being borrowed twice:
error[E0499]: cannot borrow `*x` as mutable more than once at a time

1  fn f<T>(x: &mut [T]) > Result<&mut T, &mut [T]> {
  let's call the lifetime of this reference `'1`
2  if let Some(x) = blackbox(x) {
  first mutable borrow occurs here
3  return Ok(x);
  returning this value requires that `*x` is borrowed for `'1`
4  }
5  Err(x)
 ^ second mutable borrow occurs here
Why exactly is x
borrowed twice in line 5?
For blackbox = x x.get_mut(0)
the problem is simple to solve with pattern matching
fn f(x: &mut [T]) > Result<&mut T, &mut [T]> {
match x {
[x, ..] => Ok(x),
x => Err(x),
}
}
Of course exactly one of these options must apply:

unsafe
does not have to be used to construct suchf
=> could you please tell me how to construct suchf
? 
unsafe
must be used to construct suchf
2.1) It is possible to constructf
so that it never causes UB => huh... Okay. Does any unstable feature solve this problem?
2.2)f
will cause UB => oh, ok... i really need explanation