一、环境搭建与第一行代码
C++程序员熟悉的构建工具链(g++/clang + Make/CMake)在Rust中对应:
- rustc:Rust编译器(类比g++)
- cargo:全能项目管理工具(包含CMake + Conan + Catch2功能)
创建新项目:
cargo new hello_rs # 类似CMake的模板初始化
对比Hello World:
// C++
#include
int main() {
std::cout << "Hello World!" << std::endl;
}
// Rust
fn main() {
println!("Hello World!"); // 注意宏的!后缀
}
二、基础语法特征对比
变量声明
C++模式:
int x = 5; // 可变变量
const float PI = 3.14; // 常量
Rust对应:
let x: i32 = 5; // 不可变绑定
let mut y = 10; // 可变绑定
const PI: f32 = 3.14; // 编译期常量
关键差异:
- 类型后置(类似C++11的auto声明)
- 默认不可变(const和不可变let的区别类似C++的constexpr和const)
- 强大的类型推导(比C++的auto更彻底)
基本数据类型
数值类型:
C++ | Rust | 说明 |
int | i32 | 明确位宽 |
long long | i64 | |
size_t | usize | 指针大小的无符号整数 |
char | u8/i8 | 严格区分字符和字节 |
复合类型:
// C++
std::tuple tup(1, "text");
auto [a, b] = tup; // C++17结构化绑定
// Rust
let tup: (i32, &str) = (1, "text");
let (a, b) = tup; // 模式匹配解构
三、控制流对比
条件语句
C++风格:
if (x > 5) {
// ...
} else if (x > 0) {
// ...
} else {
// ...
}
Rust版:
if x > 5 {
// ...
} else if x > 0 {
// ...
} else {
// ...
}
关键差异:
- 条件表达式不需要括号
- 可作为表达式返回值:
let result = if x > 5 { 10 } else { 0 }; // 类似三目运算符
循环结构
C++传统循环:
for (int i=0; i<10; ++i) { /*...*/ }
while (condition) { /*...*/ }
Rust现代化实现:
// 区间迭代器
for i in 0..10 { /* 0到9 */ }
for i in 0..=10 { /* 0到10 */ }
// while保持相似
while condition { /*...*/ }
// 带返回值的loop循环
let result = loop {
if condition() {
break 42; // 返回循环结果
}
};
四、函数定义对比
C++函数:
int add(int a, int b) {
return a + b;
}
Rust版本:
fn add(a: i32, b: i32) -> i32 {
a + b // 省略return,类似C++的尾返回类型
}
特别说明:
- 参数必须显式声明类型(不支持auto参数)
- 表达式结尾无分号即作为返回值
- 支持模式匹配参数解构:
fn print_coord(&(x, y): &(i32, i32)) {
println!("({}, {})", x, y);
}
五、所有权系统初探(C++程序员快速理解)
变量作用域对比
C++的RAII:
{
std::vector v = {1,2,3}; // 构造
} // 自动调用析构函数
Rust的所有权:
{
let v = vec![1,2,3]; // 分配在堆上
} // 立即释放内存(严格确定性的生命周期)
移动语义对比
C++需要显式std::move:
auto v1 = std::vector{1,2,3};
auto v2 = std::move(v1); // v1变为空
Rust默认移动:
let v1 = vec![1,2,3];
let v2 = v1; // 所有权转移,v1失效
// println!("{:?}", v1); // 编译错误!
下一章预告:中篇将深入讲解所有权系统、借用检查机制、生命周期标注,以及如何将这些概念对应到C++的移动语义、智能指针和引用机制。