Borrow checker and function arguments in Rust, correct or over zealous? [duplicate]

社会主义新天地 提交于 2019-12-17 14:24:26

问题


When a mutable argument is passed as a function argument, the borrow checker doesn't allow this to be used to construct other arguments, even when those arguments clone values without holding a reference.

While assigning variables outside the function is always an option1, logically this seems over zealous and something the borrow checker could take into account.

Is this working as intended or something that should be resolved?

#[derive(Debug)]
struct SomeTest {
    pub some_value: f64,
    pub some_other: i64,
}

fn some_fn(var: &mut SomeTest, other: i64) {
    println!("{:?}, {}", var, other);
}

fn main() {
    let mut v = SomeTest { some_value: 1.0, some_other: 2 };
    some_fn(&mut v, v.some_other + 1);

    // However this works!
/*
    {
        let x = v.some_other + 1;
        some_fn(&mut v, x);
    }
*/
}

Gives this error:

  --> src/main.rs:14:21
   |
14 |     some_fn(&mut v, v.some_other + 1);
   |                  -  ^^^^^^^^^^^^ use of borrowed `v`
   |                  |
   |                  borrow of `v` occurs here

See: playpen.


[1]: Even though one-off assignments do sometimes improve readability, being forced to use them for arguments encourages use of scopes to avoid single use variables polluting the name-space, causing function calls that would otherwise be one line - being enclosed in braces and defining variables... I'd like to avoid this if possible especially when the requirement seems like something the borrow checker could support.


回答1:


This is an artifact of the current implementation of the borrow checker. It is a well known limitation, dating back to at least 2013, and no one is overjoyed by it.

Is this working as intended

Yes.

something that should be resolved?

Yes.

The magic keywords are "non-lexical lifetimes". Right now, lifetimes are lexical - they correspond to the blocks of source that we type. Ideally, foo.method(foo.mutable_method()) would see that the borrow ends "inside the parenthesis", but for a myriad of reasons, it is tied to the entire statement.

For tons of further information see RFC issue 811 and everything linked from there.



来源:https://stackoverflow.com/questions/41421107/borrow-checker-and-function-arguments-in-rust-correct-or-over-zealous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!