// C++
std::pair<int, std::string> p = {42, "hello"};
std::tuple<int, float, std::string> t = {1, 3.14f, "world"};
rust复制代码
// Rust
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
cpp复制代码
// C++
std::vector<int> vec = {1, 2, 3};
vec.push_back(4);
rust复制代码
// Rust
let mut vec = vec![1, 2, 3]; // 宏创建
vec.push(4);
let vec2: Vec<i32> = Vec::new(); // 空向量
4. Map/Set
cpp复制代码
// C++
std::map<std::string, int> m = {{"Alice", 30}};
m["Bob"] = 25;
std::unordered_set<int> s = {1, 2, 3};
s.insert(4);
rust复制代码
// Rust
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);
// BTreeMap (有序)
use std::collections::BTreeMap;
let mut bmap = BTreeMap::new();
bmap.insert("Alice", 30);
5. Queue/Stack
cpp复制代码
// C++
std::queue<int> q;
q.push(1);
q.pop();
std::stack<int> s;
s.push(1);
s.pop();
// C++
std::priority_queue<int> pq;
pq.push(3);
pq.push(1);
pq.push(2); // 默认最大堆
rust复制代码
// Rust
use std::collections::BinaryHeap;
let mut heap = BinaryHeap::new();
heap.push(3);
heap.push(1);
heap.push(2); // 默认最大堆
7. 结构体和类
cpp复制代码
// C++
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;
}
};
rust复制代码
// Rust
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. 枚举
cpp复制代码
// C++ (enum class)
enum class Color {
Red,
Green,
Blue
};
// C++17 variant
std::variant<int, float, std::string> v = "hello";