cannot borrow as immutable because it is also borrowed as mutable

后端 未结 2 1909
滥情空心
滥情空心 2020-12-31 17:26

I\'m using the structs Foo and Bar from a library and I\'m getting a compilation error in the client code. I simplified the code to this:



        
相关标签:
2条回答
  • 2020-12-31 17:59

    You can limit the lifetime of the array variable by placing it in a new scope with curly braces ({ ... }):

    fn main() {
        let mut foo = Foo { some_str: "test" };
        {
            let mut array: [Bar; 1] = [foo.create_bar()];
            process(&mut array);
        }
        foo.read_data();
    }
    
    0 讨论(0)
  • 2020-12-31 18:22

    You original code will work as-is once non-lexical lifetimes are enabled by default:

    #![feature(nll)]
    
    use std::marker::PhantomData;
    
    struct Foo {
        some_str: &'static str,
    }
    
    struct Bar<'a> {
        some_str: &'static str,
        marker: PhantomData<&'a Foo>,
    }
    
    impl Foo {
        fn read_data(&self) {
            // add code here
        }
        fn create_bar<'a>(&'a mut self) -> Bar<'a> {
            Bar {
                some_str: "test2",
                marker: PhantomData,
            }
        }
    }
    
    fn process(_arr: &mut [Bar]) {}
    
    fn main() {
        let mut foo = Foo { some_str: "test" };
        let mut array: [Bar; 1] = [foo.create_bar()];
        process(&mut array);
        foo.read_data();
    }
    

    With NLL, the borrow checker becomes more advanced and precise; it can now understand that you aren't using array after the call to process so it is safe to use foo in a new manner.

    0 讨论(0)
提交回复
热议问题