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);

}
相关推荐
Dilee几秒前
Spring AI 核心链路拆解:ChatClient、Prompt、Advisor、ChatModel 到底怎么串起来?
后端
Cloud_Shy6188 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第六章 Item 40 - 43)
android·开发语言·人工智能·笔记·python·学习方法
半只小闲鱼14 分钟前
配置计划模块通用办公设备家具批复数合计计算
开发语言·python
qq_4221525736 分钟前
Word 文件太大怎么压缩?2026 年文档瘦身方案对比
开发语言·c#·word
charliedev41 分钟前
Jedi:Python 自动补全与静态分析的实用工具
开发语言·python·其他
无风听海41 分钟前
在 ASP.NET Core 开发环境中为自定义域名签发受信任的自签名证书—HSTS 启用后的完整实践
windows·后端·asp.net
无风听海1 小时前
深入理解 ASP.NET Core 中的UseHsts()
后端·asp.net
学编程的小程1 小时前
DISTINCT 的“惯性陷阱“:当去重操作沦为性能累赘
后端
MageGojo1 小时前
R-Shell开源项目实战解析:用Rust打造命令行SSH工具,支持连接管理、远程执行、SFTP与MCP
运维·rust·开源项目·命令行工具·ssh客户端·mcp
ji198594431 小时前
MATLAB 求散点曲线斜率
开发语言·算法·matlab