美文网首页
Rust编程语言-8-常用集合

Rust编程语言-8-常用集合

作者: onemoremile | 来源:发表于2022-01-10 23:12 被阅读0次

集合

vector

let v: Vec<i32> = Vec::new(); //显示声明元素类型是i32

let v = vec![1, 2, 3];  //通过推导得到元素类型是i32

可变vector
1)写入新的元素

    let mut v = Vec::new();

    v.push(5);
    v.push(6);
    v.push(7);
    v.push(8);

2)读取某个元素内容
一种方式是通过index索引,如&v[2],但是可能会panic,下标溢出
另一种方式是通过get(index)方式,至少会返回None,不会panic

    let v = vec![1, 2, 3, 4, 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."),
    }
  1. 迭代vector
    打印vector中元素
    let v = vec![100, 32, 57];
    for i in &v {
        println!("{}", i);
    }

修改vector中元素

    let mut v = vec![100, 32, 57];
    for i in &mut v {
        *i += 50;
    }

String

不同的初始化方式

let mut s = String::new();

let s = "initial contents".to_string();

修改String内容

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

    let mut s = String::from("lo");
    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

    fn add(self, s: &str) -> String {} //self导致s1+&s2执行后,s1被move
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");

    let s = format!("{}-{}-{}", s1, s2, s3); //比使用s1+&s2+&s3 可读性更好
let hello = "Здравствуйте";  //不是3开头,是俄文
let answer = &hello[0];

此处,hello[0]指向的可能不是一个有效的Unicode scalar value;同时这样检索效率太低,复杂度是O(1)

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

打印出如下字符:
224
164
// --snip--
165
135

But be sure to remember that valid Unicode scalar values may be made up of more than 1 byte.

HashMap

new()方式构造HashMap

    use std::collections::HashMap;

    let mut scores = HashMap::new();

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

另一种方式构造HashMap,从vector

    use std::collections::HashMap;

    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();

遍历HashMap,包括key和value

    use std::collections::HashMap;

    let mut scores = HashMap::new();

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

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

    scores.entry(String::from("Yellow")).or_insert(50);  //如果不存在再添加元素
    scores.entry(String::from("Blue")).or_insert(50);

相关文章

网友评论

      本文标题:Rust编程语言-8-常用集合

      本文链接:https://www.haomeiwen.com/subject/zkqvcrtx.html