Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active January 6, 2024 13:13
Show Gist options
  • Save max-itzpapalotl/e27a14db8231155455ef5902a4a6792f to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/e27a14db8231155455ef5902a4a6792f to your computer and use it in GitHub Desktop.
7. Vectors

7. Vectors

  • Constructing and accessing
  • Element access and bounds checking
  • The vec! macro
  • Iterating over a vector
  • Slices of vectors

Constructing and accessing

fn main() {
    let mut v : Vec<u64> = Vec::new();
    v.push(1);
    v.push(2);
    println!("{} {} {:?}", v[0], v[1], v);
}
fn main() {
    let mut v : Vec<u64> = Vec::with_capacity(3);
    v.push(1);
    v.push(2);
    println!("{} {} {:?} {} {}", v[0], v[1], v, v.len(), v.capacity());
}

Element access and bounds checking

fn main() {
    let v : Vec<u64> = vec![1,2,3];
    println!("{}", v[3]);
}
cargo run
cargo run --release
fn main() {
    let mut v : Vec<u64> = vec![1,2,3];
    v[1] = 12;
    println!("{:?}", v);
}

The vec! macro

fn main() {
    let v : Vec<u64> = vec![1,2,3];
    let w : Vec<i64> = vec![17; 3];
    let u = vec![17u32; 4];
    println!("{:?} {:?} {:?}", v, w, u);
}

Iterating over a Vectors

fn main() {
    let v : Vec<u64> = vec![1,2,3];
    for x in v.iter() {
    // for x in &v {
    // for x in v {
    // for x in v.into_iter() {
        println!("{}", x);
    }
}
fn main() {
    let mut v : Vec<u64> = vec![1,2,3];
    for x in &mut v {
    // for x in v.iter_mut() {
        *x += 1;
        println!("{}", x);
    }
}
fn main() {
    let v : Vec<u64> = vec![1,2,3];
    let w : Vec<u64> = v.iter().map(|x| 2*x).collect();
    println!("{:?}", w);
}

Slices of Vectors

fn main() {
    let v : Vec<u64> = vec![1,2,3];
    let w = &v[0..1];
    let u = &v[0..=1];
    println!("{:?}", w);
}
fn main() {
    let mut v : Vec<u64> = vec![1,2,3];
    let w = &v[1];
    println!("{:?}", w);
    let u = &mut v[2];
    *u = 12;
    println!("{:?}", u);
}

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment