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

介绍

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

Rust相关的源码资料在:https://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不允许别名存在的原因
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值