007 Rust死灵书笔记之引用与别名

介绍

本系列录制的视频主要放在B站上Rust死灵书学习视频

Rust相关的源码资料在:github.com/anonymousGiga

笔记内容

引用与别名

在Rust中,存在两种引用类型,分别是:

  • 引用
  • 借用(也就是可变引用)

遵循规则:

  • 引用的生命周期不能超过被引用的内容(原因:Rust中内存在拥有它的变量离开作用域后就被自动释放)
  • 可变引用不能存在别名

下面通过代码阐述:

fn main() {
    //1、引用的生命周期不能超过被引用的内容
    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、可变引用不存在别名:这里的别名的定义同C++中别名的定义,而不是说的类型别名
//例如c++中,别名:int a = 10; int &b = a; b为a的别名
//原因:

//考虑如下函数:
//fn compute(input: &u32, output: &mut u32) {
//    if *input > 10 {
//        *output = 1;
//    }
//    if *input > 5 {
//        *output *= 2;
//    }
//}

//可能的优化:
fn compute(input: &u32, output: &mut u32) {
    let cached_input = *input; // 将*input放入缓存
    if cached_input > 10 {
        *output = 1; // x > 10 则必然 x > 5,所以直接加倍并立即退出
    } else if cached_input > 5 {
        *output *= 2;
    }
}
//如果存在别名,则会如下:
//                    //  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

//所以,这就是为什么Rust不允许别名存在的原因
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商