[][src]Function tao_of_rust::ch05::borrow::borrow_check

pub fn borrow_check()

借用检查

Base usage: 借用检查保证了内存安全 试想,input 和 output 如果将同一个变量的 不可变和可变引用同时传入会发生什么?

fn compute(input: &u32, output: &mut u32) {
    if *input > 10 {
        *output = 1;
    }
    if *input > 5 {
        *output *= 2;
    }
}
fn main() {
    let i = 20;
    let mut o = 5;
    compute(&i, &mut o); // o = 2
 // let mut i = 20;
 // compute(&i, &mut i);  // 借用检查不会允许该行编译成功
}Run

Base usage: 优化该函数

fn compute(input: &u32, output: &mut u32) {
    let cached_input = *input;
    if cached_input > 10 {
        *output = 2;
    } else if cached_input > 5 {
        *output *= 2;
    }
}
fn main() {
   let i = 20;
   let mut o = 5;
   compute(&i, &mut o); // o = 2
}Run