Rust - Grundlagen - 08 - Collections

Collections

Verständnis

  • Vektor

    // 声明方式 1 - 不可变、new、指定类型
    let v: Vec<i32> = Vec::new();
    // 声明方式 2 - 使用 macro
    let v = vec![1, 2, 3];
    // 声明方式 3 - 可变、new、后续 push 时自动指定类型
    let mut v = Vec::new();
    v.push(5);
    
    // 获取元素
    let v = vec![1, 2, 3, 4, 5];
    // 如果越界就 panic
    let third: &i32 = &v[2];
    println!("The third element is {}", third);
    // 如果越界则可以在 None 分支处理
    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;
    }
    
    // 虽然 Vector 只能支持一种类型,但是可以通过 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

    // 初始化方式 1 - new
    let mut s = String::new();
    // 初始化方式 2 - to_string
    let data = "initial contents";
    let s = data.to_string();
    
    // 拼接方式 1 - push_str
    s.push_str("bar");
    // 拼接方式 2 - push
    s.push('l');
    // 拼接方式 3 - +
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2;  // s1 被 move
    // 拼接方式 4 - format!
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");
    let s = format!("{}-{}-{}", s1, s2, s3);
    
    // string 在 Rust 里有三种表现形式
    "नमस्ते"
    // Bytes 字节、 Scalar Values 标量值、 Grapheme Clusters 字素。依次表现如下
    [224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,
    224, 165, 135]  // for b in "नमस्ते".bytes()
    ['न', 'म', 'स', '्', 'त', 'े']  // for b in "नमस्ते".chars()
    ["न", "म", "स्", "ते"]  // 标准库没有提供可用于 for-in 迭代函数
    // 取 string 部分值的时候,无法直接用 index 获取
    // let s1 = String::from("hello"); let h = s1[0];
    // 可以用 slice
    let hello = "Здравствуйте";  // 这里每个字素都需要 2 个 Bytes 存储
    let s = &hello[0..4];  // 但需要注意 range 范围合法,这里如果是 [0..1] 则会运行时 panic
    
  • HashMap

    // 初始化
    let mut scores = HashMap::new();
    // 新增/覆盖值
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    // 获取值
    let score = scores.get(&color);
    // for-in
    for (key, value) in &scores {
        println!("{}: {}", key, value);
    }
    // 不存在则新增
    scores.entry(String::from("Yellow")).or_insert(50);
    scores.entry(String::from("Blue")).or_insert(50);
    

Quelle

https://doc.rust-lang.org/std/collections/index.html https://doc.rust-lang.org/book/ch08-00-common-collections.html

…

Methoden zum Iterieren über Strings

Glücklicherweise kann man auf andere Weise auf String-Elemente zugreifen.

Für einzelne Unicode-Skalarwerte verwendet man am besten die Methode chars. Der Aufruf von chars auf „नमस्ते“ trennt sechs Werte vom Typ char ab; über das Ergebnis kann iteriert werden:


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

Die Methode bytes gibt jedes rohe Byte zurück und kann je nach Anwendungsfall passend sein:


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

Gültige Unicode-Skalarwerte können aus mehr als einem Byte bestehen. Graphemcluster aus Strings zu erhalten ist komplex; die Standardbibliothek stellt diese Funktion daher nicht bereit. Falls nötig, gibt es dafür Crates auf crates.io .