Skip to content

常见集合

Vector

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fn main() {
    // Definition
    let v: Vec<i32> = Vec::new();
    dbg!(v);
    let mut v = vec![1,2,3];
    println!("{:?}",v);

    // add
    v.push(5);


    // get
    let two = &v[1];
    println!("{}",two);

    let not_exist = v.get(100); // 返回None

    // delete
    v.remove(0);

    // tranverse
    for i in &v {
        println!("{}", i);
    }
    for i in &mut v {
        *i += 50;
    }
}

String

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn main() {
    // definition
    let mut s = String::new();
    let data = "init";
    let s = data.to_string();
    let mut s = String::from("init");

    // update
    s.push_str("test");
    s.push('l');

    let s1 = String::from("hello ");
    let s2 = String::from("world");
    let s3 = s1 + &s2; // s 被移动, 不能使用 add(self, s:&str)->String

    let s = format!("{}-{}", s3, s2);

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

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

    for c in "hello world".split_whitespace() {
        println!("{}", c);
    }
}

Map

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
fn main() {
    // definition
    use std::collections::HashMap;
    let mut scores = HashMap::new();
    // insert
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    let key = String::from("key");
    scores.insert(key, 2); // key丧失所有权

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

    // get
    let score = scores.get(&"Blue".to_string());

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

    // update
    // 直接覆盖
    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Blue"), 25);

    println!("直接覆盖 {:?}", scores); // blue 25

    // 没有键时插入
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);

    scores.entry(String::from("Yellow")).or_insert(50);
    scores.entry(String::from("Blue")).or_insert(50);

    println!("{:?}", scores); // blue 10, yellow 50

    // 根据旧值更新新值
    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;
    }

    println!("{:?}", map); // world:2, hello:1, wonderful: 1

    // delete
    m.remove(&k);
}