Citation and alias of 007 rust necromancer notes

Time:2021-4-30

introduce

The video recorded in this series is mainly on station BRust necromancer learning video

The source code of rust is as follows:github.com/anonymousGiga

Note content

References and aliases

In rust, there are two types of references

  • quote
  • Borrowing (i.e. variable reference)

Follow the rules:

  • The life cycle of a reference cannot exceed the referenced content (reason: there is a variable in rust that owns it and is automatically released after it leaves the scope)
  • Variable references cannot have aliases

The following is explained by code:

fn main() {
    //1. The lifecycle of a reference cannot exceed the referenced content
    let a = String::from("This is a!");
    let mut b = &a;
    {
        let c = String::from("This is c!");
        b = &c;
        println!("reference c: {}", b);
    }

    //println!("reference c: {}", b);


    println!("Hello, world!");
}
//2. Variable reference does not have alias: the definition of alias here is the same as that in C + +, not the type alias
//For example, in C + +, alias: int a = 10; int &b = a;  B is the alias of A
//Reason:

//Consider the following function:
//fn compute(input: &u32, output: &mut u32) {
//    if *input > 10 {
//        *output = 1;
//    }
//    if *input > 5 {
//        *output *= 2;
//    }
//}

//Possible optimizations:
fn compute(input: &u32, output: &mut u32) {
    let cached_ input = *input; //  Put * input into cache
    if cached_input > 10 {
        *output = 1; //  If x > 10, x > 5 is inevitable, so double and exit immediately
    } else if cached_input > 5 {
        *output *= 2;
    }
}
//If there is an alias, it will be as follows:
//                    //  input ==  output == 0xabad1dea
//                    // *input == *output == 20
//if *input > 10 {    // true  (*input == 20)
//    *output = 1;    // also overwrites *input, because they are the same
//}
//if *input > 5 {     // false (*input == 1)
//    *output *= 2;
//}
//                    // *input == *output == 1

//So that's why rust doesn't allow aliases

This work adoptsCC agreementReprint must indicate the author and the link of this article

Linghu Yichong