C++类型和容器在Rust中的对应关系
基本类型对应关系
| C++ 类型/特性 |
Rust 对应 |
说明 |
| 数组 T[] |
[T; N] |
固定大小数组 |
| std::array<T, N> |
[T; N] |
固定大小数组 |
| std::pair<T, U> |
(T, U) |
元组或自定义结构体 |
| std::tuple<Ts…> |
(T1, T2, ...) |
元组 |
| struct/class |
struct |
Rust只有struct,默认所有成员私有 |
| enum class |
enum |
Rust枚举更强大,可携带数据 |
| lambda |
闭包 \|params\| { body } |
语法不同但功能相似 |
| variant (C++17) |
enum 或第三方库 |
Rust枚举天然就是带数据的联合体 |
容器对应关系
线性容器
| C++ 容器 |
Rust 对应 |
说明 |
| std::vector |
Vec<T> |
动态数组,功能几乎相同 |
| std::list |
LinkedList<T> |
双向链表,但使用较少 |
| std::deque |
VecDeque<T> |
双端队列 |
关联容器
| C++ 容器 |
Rust 对应 |
说明 |
| std::map<K, V> |
BTreeMap<K, V> |
有序映射(基于B树) |
| std::unordered_map<K, V> |
HashMap<K, V> |
哈希映射 |
| std::set |
BTreeSet<T> |
有序集合 |
| std::unordered_set |
HashSet<T> |
哈希集合 |
适配器容器
| C++ 容器 |
Rust 对应 |
说明 |
| std::stack |
Vec<T> (模拟) |
Rust标准库无专门栈 |
| std::queue |
VecDeque<T> (模拟) |
可用VecDeque模拟 |
| std::priority_queue |
BinaryHeap<T> |
二叉堆 |
详细对比和示例
1. 数组
int arr[5] = {1, 2, 3, 4, 5};
std::array<int, 5> std_arr = {1, 2, 3, 4, 5};
let arr: [i32; 5] = [1, 2, 3, 4, 5];
let arr_inferred = [1, 2, 3, 4, 5];
2. Pair/Tuple
std::pair<int, std::string> p = {42, "hello"};
std::tuple<int, float, std::string> t = {1, 3.14f, "world"};
let p: (i32, String) = (42, "hello".to_string());
let t: (i32, f32, String) = (1, 3.14, "world".to_string());
let (x, y) = p;
3. Vector
std::vector<int> vec = {1, 2, 3};
vec.push_back(4);
let mut vec = vec![1, 2, 3];
vec.push(4);
let vec2: Vec<i32> = Vec::new();
4. Map/Set
std::map<std::string, int> m = {{"Alice", 30}};
m["Bob"] = 25;
std::unordered_set<int> s = {1, 2, 3};
s.insert(4);
use std::collections::{HashMap, HashSet};
let mut m = HashMap::new();
m.insert("Alice".to_string(), 30);
m.insert("Bob".to_string(), 25);
let mut s = HashSet::new();
s.insert(1);
s.insert(2);
s.insert(3);
use std::collections::BTreeMap;
let mut bmap = BTreeMap::new();
bmap.insert("Alice", 30);
5. Queue/Stack
std::queue<int> q;
q.push(1);
q.pop();
std::stack<int> s;
s.push(1);
s.pop();
use std::collections::VecDeque;
let mut queue = VecDeque::new();
queue.push_back(1);
queue.pop_front();
let mut stack = Vec::new();
stack.push(1);
stack.pop();
6. Priority Queue
std::priority_queue<int> pq;
pq.push(3);
pq.push(1);
pq.push(2);
use std::collections::BinaryHeap;
let mut heap = BinaryHeap::new();
heap.push(3);
heap.push(1);
heap.push(2);
7. 结构体和类
class Person {
private:
std::string name;
int age;
public:
Person(std::string n, int a) : name(n), age(a) {}
void print() const {
std::cout << name << ": " << age << std::endl;
}
};
struct Person {
name: String,
age: u32,
}
impl Person {
fn new(name: String, age: u32) -> Self {
Person { name, age }
}
fn print(&self) {
println!("{}: {}", self.name, self.age);
}
}
8. 枚举
enum class Color {
Red,
Green,
Blue
};
std::variant<int, float, std::string> v = "hello";
enum Color {
Red,
Green,
Blue,
}
enum WebEvent {
PageLoad,
KeyPress(char),
Click { x: i64, y: i64 },
}
let event = WebEvent::Click { x: 10, y: 20 };
9. Lambda/闭包
auto add = [](int a, int b) -> int { return a + b; };
auto result = add(3, 4);
let add = |a: i32, b: i32| -> i32 { a + b };
let result = add(3, 4);
let add_inferred = |a, b| a + b;
10. Variant (Rust枚举实现)
std::variant<int, float, std::string> v = "hello";
enum MyVariant {
Int(i32),
Float(f32),
String(String),
}
let v = MyVariant::String("hello".to_string());
match v {
MyVariant::Int(i) => println!("Integer: {}", i),
MyVariant::Float(f) => println!("Float: {}", f),
MyVariant::String(s) => println!("String: {}", s),
}
重要区别
所有权系统
- Rust: 严格的所有权、借用和生命周期系统
- C++: RAII和智能指针,但不如Rust严格
默认行为
- Rust: 变量默认不可变,需要
mut关键字使其可变
- C++: 变量默认可变
内存安全
- Rust: 编译时保证内存安全,无数据竞争
- C++: 需要程序员手动管理
错误处理
- Rust:
Result<T, E> 和 Option<T> 类型
- C++: 异常或错误码
泛型
- Rust: Trait约束的泛型,编译时单态化
- C++: 模板,编译时代码生成
Rust特有特性
| Rust 特性 |
C++ 对应 |
说明 |
| Option |
std::optional<T> (C++17) |
表示可能有值或无值 |
| Result<T, E> |
异常或std::expected (C++23) |
表示成功或错误 |
| Slice &[T] |
std::span<T> (C++20) |
连续序列的视图 |
| Trait |
抽象类/概念 (C++20) |
定义共享行为 |
| Pattern Matching |
switch + 结构化绑定 |
Rust的match更强大 |
| 迭代器 |
std::iterator |
Rust迭代器更安全易用 |
使用建议
- 学习曲线: Rust的所有权系统需要适应,但能带来更好的安全性
- 性能: Rust性能与C++相当,但更安全
- 并发: Rust的并发模型更安全,编译时防止数据竞争
- 生态系统: C++更成熟,Rust正在快速发展
- 适用场景:
- 系统编程、嵌入式、WebAssembly: 两者都适合
- 需要绝对内存安全: 选择Rust
- 已有C++代码库: 考虑C++或Rust FFI集成
Rust和C++在类型和容器方面有很多相似之处,但Rust通过所有权系统和更强大的类型系统提供了更好的内存安全和并发安全性。
所有评论(0)