This trait would, besides being convenient for avoiding methods nesting, prevent common occurrences of Error[0499]: cannot borrow * more than once.
This trait would look something similar to this
pub trait Then{
fn then<Out, F: FnOnce(Self) -> Out>(self, operator: F) -> Out
where Self: Sized
{
operator(self)
}
}
and would be default implemented for any generic type T
.
If we want to mutably borrow a variable in a nested method while also borrowing it in the surrounding method, this will currently lead to an Error[4099]:
struct Foo();
impl Foo{
pub fn baz(&mut self, bar: Bar){}
}
struct Bar();
impl Bar{
pub fn new(foo: &mut Foo) -> Self{
Bar()
}
}
fn main() {
let mut foo = Foo();
foo.baz(Bar::new(&mut foo));
}
error[E0499]: cannot borrow `foo` as mutable more than once at a time
--> src/main.rs:19:22
|
19 | foo.foo(Bar::new(&mut foo));
| --- --- ^^^^^^^^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
To avoid this, one would need to bind Bar let mut bar = Bar::new(&mut foo)
and then call foo.baz(bar) but this trait would allow one to avoid this like so:
Bar::new(&mut foo).then(|bar| foo.baz(bar));