第一个程序:从零开始

原理

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

C: 变量与数据类型


语法

基本结构

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"; // 允许

基本类型

类型含义例子
i3232位有符号整数(默认)42
f6464位浮点数(默认)3.14
bool布尔值true, false
charUnicode 字符(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 自检

  1. let x = 5; let x = x + 1;let mut x = 5; x = 6; 的本质区别是什么?
  2. 整数除法 10/3=3 的原因是什么?想得到 3.333 该怎么做?