Rust - Basic - 08 - Collections

Collections

Comprehension

  • vector

    // declaration 1 - immutable, new, explicit type
    let v: Vec<i32> = Vec::new();
    // declaration 2 - using a macro
    let v = vec![1, 2, 3];
    // declaration 3 - mutable, new, type inferred when pushing
    let mut v = Vec::new();
    v.push(5);
    
    // access an element
    let v = vec![1, 2, 3, 4, 5];
    // panics if out of bounds
    let third: &i32 = &v[2];
    println!("The third element is {}", third);
    // handle out-of-bounds access in the None branch
    match v.get(2) {
        Some(third) => println!("The third element is {}", third),
        None => println!("There is no third element."),
    }
    
    // iterate
    let v = vec![100, 32, 57];
    for i in &v {
        println!("{}", i);
    }
    // mutable iteration
    let mut v = vec![100, 32, 57];
    for i in &mut v {
        *i += 50;
    }
    
    // although a vector supports one type, an enum can extend it
    enum SpreadsheetCell {
        Int(i32),
        Float(f64),
        Text(String),
    }
    
    let row = vec![
        SpreadsheetCell::Int(3),
        SpreadsheetCell::Text(String::from("blue")),
        SpreadsheetCell::Float(10.12),
    ];
    
  • string

    // initialization 1 - new
    let mut s = String::new();
    // initialization 2 - to_string
    let data = "initial contents";
    let s = data.to_string();
    
    // concatenation 1 - push_str
    s.push_str("bar");
    // concatenation 2 - push
    s.push('l');
    // concatenation 3 - +
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2;  // s1 is moved
    // concatenation 4 - format!
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");
    let s = format!("{}-{}-{}", s1, s2, s3);
    
    // strings have three representations in Rust
    "नमस्ते"
    // Bytes, Scalar Values, and Grapheme Clusters, shown below
    [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()
    ["न", "म", "स्", "ते"]  // the standard library does not provide a function for for-in iteration
    // string slices cannot be accessed directly by index
    // let s1 = String::from("hello"); let h = s1[0];
    // use a slice
    let hello = "Здравствуйте";  // each grapheme here requires 2 bytes of storage
    let s = &hello[0..4];  // ensure the range is valid; [0..1] would panic at runtime
    
  • hash map

    // initialization
    let mut scores = HashMap::new();
    // add or overwrite a value
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    // get a value
    let score = scores.get(&color);
    // for-in
    for (key, value) in &scores {
        println!("{}: {}", key, value);
    }
    // insert if absent
    scores.entry(String::from("Yellow")).or_insert(50);
    scores.entry(String::from("Blue")).or_insert(50);
    

Origin

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

…

Methods for Iterating Over Strings

Fortunately, you can access elements in a string in other ways.

If you need to perform operations on individual Unicode scalar values, the best way to do so is to use the chars method. Calling chars on “नमस्ते” separates out and returns six values of type char, and you can iterate over the result to access each element:


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

This code will print the following:


न
म
स
्
त
े

The bytes method returns each raw byte, which might be appropriate for your domain:


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

This code will print the 18 bytes that make up this String:


224
164
// --snip--
165
135

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

Getting grapheme clusters from strings is complex, so this functionality is not provided by the standard library. Crates are available on  crates.io  if this is the functionality you need.