Rust Lang Book: Ch.8 Common Collections: vec, string, hashmap, hashset

Vector

   let v: Vec<i32> = Vec::new();//实例化
{
   let v = vec![1, 2, 3];//Rust自动推测类型
}//出了作用域自动析构
   v.push(5);
   v.push(6);
   let third: &i32 = &v[2];//[]会得到一个引用,如果不存在就panic
   println!("The third element is {}", third);

   match v.get(2) {//get方法会取到Option<&T>
       Some(third) => println!("The third element is {}", third),
       None => println!("There is no third element."),
   }

  

let mut vec = Vec::new();
vec.push(1);
vec.push(2);

assert_eq!(vec.len(), 2);
assert_eq!(vec[0], 1);

assert_eq!(vec.pop(), Some(2));
assert_eq!(vec.len(), 1);

vec[0] = 7;
assert_eq!(vec[0], 7);

vec.extend([1, 2, 3].iter().copied());

for x in &vec {
    println!("{}", x);
}
assert_eq!(vec, [7, 1, 2, 3]);

Rust保证引用的有效性,因此,从vector中取了引用之后,在用完之前都不能够再修改这个vector。

    let mut v = vec![1, 2, 3, 4, 5];

    let first = &v[0];
                  - immutable borrow occurs here

    v.push(6);
   ^^^^^^^^^ mutable borrow occurs here
    println!("The first element is: {}", first);

  

遍历时需要用borrowed form:

    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;//i也是mutable
    }

  

如果需要一个vector同时存好几种数据,可以试着把vec和enum结合:

    enum SpreadsheetCell {
        Int(i32),
        Float(f64),
        Text(String),
    }

    let row = vec![
        SpreadsheetCell::Int(3),
        SpreadsheetCell::Text(String::from("blue")),
        SpreadsheetCell::Float(10.12),
    ];

  

String

String在Rust标准库中实现,在核心库中没有。String是可增长,可更改,UTF8格式的字符串。OsString, OsStr, CStr和CString则与String不同,在内存中表示方法不同或者编码不同。

//初始化
    let mut s = String::new();
    let s = "initial contents".to_string();
    let s = String::from("initial contents");
    let hello = String::from("السلام عليكم");
    let hello = String::from("Dobrý den");
    let hello = String::from("Hello");
    let hello = String::from("שָׁלוֹם");
    let hello = String::from("नमस्ते");
    let hello = String::from("こんにちは");
    let hello = String::from("안녕하세요");
    let hello = String::from("你好");
    let hello = String::from("Olá");
    let hello = String::from("Здравствуйте");
    let hello = String::from("Hola");

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

    let s3 = s1 + &s2; //concatenation
    let s = s1 + "-" + &s2 + "-" + &s3;

    let s = format!("{}-{}-{}", s1, s2, s3);//format!, 和println!操作方式一致

  

Rust不允许通过[]方法直接访问字符串中的字符,而是需要s.bytes()或者s.chars()方式遍历:

let hello = "Здравствуйте";

let s = &hello[0..4];//前4个byte


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

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

  

HashMap

    use std::collections::HashMap;

    let mut scores = HashMap::new();

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

  

    use std::collections::HashMap;

    let teams = vec![String::from("Blue"), String::from("Yellow")];
    let initial_scores = vec![10, 50];

    let mut scores: HashMap<_, _> =//zip自动创建了tuple
        teams.into_iter().zip(initial_scores.into_iter()).collect();//collect能自动将数据转化为指定的collection types

  

    let score = scores.get(&team_name); //返回Option<&V>

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

  

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

    scores.entry(String::from("Yellow")).or_insert(50);//如果没有则加入

     let count = map.entry(word).or_insert(0);//获取mutable reference
     *count += 1;//直接更改这个reference

  

HashMap默认是siphash(https://www.131002.net/siphash/siphash.pdf),这个hash不是最快的,但是可以提供对DDos的一定防护。

HashSet

use std::collections::HashSet;
// Type inference lets us omit an explicit type signature (which
// would be `HashSet<String>` in this example).
let mut books = HashSet::new();

// Add some books.
books.insert("A Dance With Dragons".to_string());
books.insert("To Kill a Mockingbird".to_string());
books.insert("The Odyssey".to_string());
books.insert("The Great Gatsby".to_string());

// Check for a specific one.
if !books.contains("The Winds of Winter") {
    println!("We have {} books, but The Winds of Winter ain't one.",
             books.len());
}

// Remove a book.
books.remove("The Odyssey");

// Iterate over everything.
for book in &books {
    println!("{}", book);
}

  

原文地址:https://www.cnblogs.com/xuesu/p/13874097.html