Rust基础-part2-变量和可变类型

Rust基础[part2]_变量和可变类型

可变变量与不可变变量

可以不指定数据类型

可变变量------mutable

rust 复制代码
fn immutable() {
    let x = 5;
    println!("The value of x is: {}", x);
}

不可变变量------immutable

rust 复制代码
fn mutable() {
    let mut y = 10;
    println!("The value of y is: {}", y);
    y = 15;
    println!("The value of y is now: {}", y);
}

常量------constants

  • 需要制定明确的数据类型,并且需要使用大写字母

  • 需要使用常量表达式进行赋值

  • 不支持重定义(遮蔽)

rust 复制代码
const NUM: i32 = 5;
const THREE_HOURS: i32 = 60 * 60 * 3;

不可变量和常量的区别

  • 常量在编译期就就确定了值,不能在运行时进行改变; 不可变量知道运行期才能确认下来。
  • 常量不可修改,不可变变量可以通过shadowing来进行修改
  • 常量必须声明类型,不可变变量不需要声明类型。
  • 常量必须使用大写字母。

静态变量------static

需要通过mut来指定可变, unsafe 块是必须的,因为静态变量在多线程环境中可能会引发数据竞争问题。

rust 复制代码
static mut NUMBER: i32 = 10;

fn static_num() {
    unsafe {
        println!("static NUMBER: {}", NUMBER);
    }// 这里可以访问静态变量NUMBER 
}

作用域scope和遮蔽shadowing

rust 复制代码
fn binding() {
    // 绑定生存于main函数中
    let long_lived_binding = 1;
    
    // 代码块, 比main函数拥有更小的作用域
    {
        // 绑定生存于代码块中
        // 这里的short_lived_binding只在这个代码块中有效
        let short_lived_binding = 2;
        println!("short_lived_binding: {}", short_lived_binding);
        // 遮蔽,在作用域中可以遮蔽成功
        let short_lived_binding = 3;
        println!("short_lived_binding after shadowing: {}", short_lived_binding);

        println!("long_lived_binding: {}", long_lived_binding);
        // 遮蔽长期绑定的变量
        // 这里的long_lived_binding会遮蔽外层的同名变量
        let long_lived_binding = 4;
        println!("long_lived_binding after shadowing: {}", long_lived_binding);
    }
    println!("long_lived_binding after block: {}", long_lived_binding);
    // println!("short_lived_binding after block: {}", short_lived_binding); // 这里会报错,因为short_lived_binding在代码块外不可见
    // 遮蔽长期绑定的变量
    let long_lived_binding = 5_f32;
    println!("long_lived_binding after shadowing: {}", long_lived_binding);

}
相关推荐
lsx20240613 小时前
Python3 SMTP发送邮件教程
开发语言
懈尘13 小时前
从 Java 1.7 到 Java 21:逐版本深入解析新特性与平台演进
java·开发语言
Honmaple13 小时前
OpenClaw 实战经验总结
后端
凉辰13 小时前
使用uni.createInnerAudioContext()播放指定音频(踩坑分享功能)
开发语言·javascript·音视频
Hello.Reader13 小时前
Rocket Fairings 实战把全局能力做成“结构化中间件”
中间件·rust·rocket
hello 早上好13 小时前
05_Java 类加载过程
java·开发语言
PPPPPaPeR.14 小时前
光学算法实战:深度解析镜片厚度对前后表面折射/反射的影响(纯Python实现)
开发语言·python·数码相机·算法
橙露14 小时前
Java并发编程进阶:线程池原理、参数配置与死锁避免实战
java·开发语言
froginwe1114 小时前
C 标准库 - `<float.h>`
开发语言
golang学习记14 小时前
Go 嵌入结构体方法访问全解析:从基础到进阶陷阱
后端