Arrays and slices

Contents

Arrays and slices#

A fixed-size array [T; N] lives inline; a slice &[T] borrows a contiguous run.

Fixed-size array.

let xs: [i32; 3] = [1, 2, 3];

Slice borrows a sub-range.

let sub: &[i32] = &xs[1..3];     // &[2, 3]

Vec<T> is the heap-allocated growable form.

let v: Vec<i32> = vec![1, 2, 3];

Borrow a Vec as a slice; & coerces Vec<T> to &[T].

let s: &[i32] = &v;

Iterate by borrow.

for x in &xs {
    println!("{x}");
}

The growable container catalog (HashMap, BTreeMap, VecDeque, HashSet) lives in std::collections; see Data Structures.

use std::collections::HashMap;
let mut m: HashMap<String, u32> = HashMap::new();
m.insert("port".into(), 8080);

References#