(done) 速通 rustlings(4) 变量声明

rust 声明变量使用 let 关键字。

rust 会自动推导变量类型,但也可以通过 : i32 明确变量类型

rust 复制代码
fn main() {
    // TODO: Add the missing keyword.
    let x = 5;
    let y: i32 = 6;

    println!("x has the value {x}");
    println!("y has the value {y}");
}

如果仅使用 let 声明变量但不初始化,是非法的,因为 rust 无法推断变量类型:

rust 复制代码
let x;

但显式声明变量类型后,可以不初始化:

rust 复制代码
let x: i32;

但若后续要使用该变量,则必须先初始化,否则非法:

rust 复制代码
    let y: i32;
    y = 42;
    println!("Number {y}");
相关推荐
shimly1234563 小时前
(done) 速通 rustlings(11) 向量vector及其操作
rust
shimly1234563 小时前
(done) 速通 rustlings(3) intro1 println!()
rust
shimly1234563 小时前
(done) 速通 rustlings(12) 所有权
rust
shimly1234564 小时前
(done) 速通 rustlings(7) 全局变量/常量
rust
敲敲了个代码4 小时前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
开发语言·前端·javascript·后端·rust
lpfasd1235 小时前
Tauri 中实现自更新(Auto Update)
rust·tauri·update
shimly1234565 小时前
(done) 速通 rustlings(10) 基本数据类型
rust
shimly1234565 小时前
(done) 速通 rustlings(8) 函数
rust
busideyang5 小时前
MATLAB vs Rust在嵌入式领域的角色定位
开发语言·matlab·rust