第一个程序:从零开始
原理
Rust 程序入口是 fn main(),编译器在链接时寻找该符号作为 CRT(C Runtime)调用起点。let 声明的变量默认不可变(immutable by default),编译器将变量名映射到栈上或寄存器中的确定位置,拒绝二次赋值。这与 C 的 const int 语义类似,但默认生效。
println! 宏在编译期展开为对 std::io::_print 的调用,格式化字符串在编译期通过 format_args! 做类型检查,避免了 C printf 的运行时不匹配问题。
数字运算对于整数默认溢出时在 debug 模式 panic,release 模式则进行二进制补码回绕(two’s complement wrapping)。
语法
基本结构
fn main() {
let name = "小明";
let age: i32 = 18; // 显式类型标注
println!("我叫{},今年{}岁。", name, age);
}变量与不可变性
let x = 5;
// x = 6; // 编译错误:cannot assign twice to immutable variable
let mut y = 5;
y = 6; // 合法变量遮蔽 (Shadowing)
let x = 5;
let x = x + 1; // 新 x 遮蔽旧 x,类型可以不同
let x = "hello"; // 允许基本类型
| 类型 | 含义 | 例子 |
|---|---|---|
i32 | 32位有符号整数(默认) | 42 |
f64 | 64位浮点数(默认) | 3.14 |
bool | 布尔值 | true, false |
char | Unicode 字符(4字节) | '好' |
&str | 字符串切片引用 | "hello" |
运算
let a = 10;
let b = 3;
println!("{}+{}={}", a, b, a + b); // 10+3=13
println!("{}/{}={}", a, b, a / b); // 10/3=3(整数截断)
println!("{}/{}={}", 10.0/3.0, f64); // 3.333...占位符
println!("{0} + {1} = {2}", x, y, x + y); // 按索引
println!("{name} {age}", name="小明", age=18); // 按命名注释
// 单行注释
/* 多行注释 */常见错误
| 错误 | 原因 |
|---|---|
| 忘记分号 | 每条语句必须以 ; 结尾 |
| 单引号字符串 | '你好' 是 char,字符串用 "你好" |
| 类型不匹配 | let x: i32 = "hello" 编译失败 |
实践
力扣问题
力扣: 力扣字符输出题
fn main() {
let c = "*";
println!(" {}", c);
println!(" {}{}{}", c, c, c);
println!("{}{}{}{}{}", c, c, c, c, c);
}力扣: 力扣入门练习
fn main() {
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
let nums: Vec<i64> = input
.split_whitespace()
.map(|s| s.parse().unwrap())
.collect();
println!("{}", nums[0] + nums[1]);
}AI 自检
let x = 5; let x = x + 1;和let mut x = 5; x = 6;的本质区别是什么?- 整数除法
10/3=3的原因是什么?想得到 3.333 该怎么做?