Back

Rust 集合

变长列表

// 创建

let v: Vec<i32> = Vec::new();
let v = vec![1, 2, 3];

// 修改
let mut v = Vec::new();
v.push(5);

// 访问
let third: &i32 = &v[2];
println!("The third element is {}", third);
match v.get(2) {
    Some(third) => println!("The third element is {}", third),
    None => println!("There is no third element."),
}

// 遍历
let v = vec![100, 32, 57];
for i in &v {
    println!("{}", i);
}
let mut v = vec![100, 32, 57];
for i in &mut v {
    *i += 50;
}

在有引用的情况下无法对列表进行修改。

UTF-8 字符串

// 创建

let mut s = String::new();

// 更新

let mut s = String::from("foo");
s.push_str("bar");
s.push('l');

// 合并

let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used

// 格式化

let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");

let s = format!("{}-{}-{}", s1, s2, s3); // do not take onwership

字符串内部对 Vec<u8> 进行包装。不支持直接索引。

切片

let hello = "Здравствуйте"; // each of these characters was 2 bytes

let s = &hello[0..4]; // s == Зд

let s = &hello[0..1]; // panic at runtime in the same way as if an invalid index were accessed in a vector

遍历

for c in "नमस्ते".chars() {
    println!("{}", c);
}
for b in "नमस्ते".bytes() {
    println!("{}", b);
}

哈希表

对于不支持 Copy 特征的对象,哈希表将获取其所有权。

// 创建

use std::collections::HashMap;
let mut scores = HashMap::new();

// 修改
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25);
scores.insert(String::from("Yellow"), 50);
scores.entry(String::from("Yellow")).or_insert(50);

let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let mut scores: HashMap<_, _> =
    teams.into_iter().zip(initial_scores.into_iter()).collect();

// 访问

let team_name = String::from("Blue");
let score = scores.get(&team_name);

// 遍历

for (key, value) in &scores {
    println!("{}: {}", key, value);
}

entry.or_insert 返回一个可变引用。

let text = "hello world wonderful world";

let mut map = HashMap::new();

for word in text.split_whitespace() {
    let count = map.entry(word).or_insert(0);
    *count += 1;
}