nandi/rustnimpublic Fork 0
7db79919131ab55e23a1730bf78c360e05d9977e
Commits
Clone
git clone https://git.rickub.com/nandi/rustnim.git
git clone ssh://git@rickub.com/nandi/rustnim.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 · on 7db79919131ab55e23a1730bf78c360e05d9977e · nandithebull · 16h ago
023-slice-iterators.rs · 57 lines · 1.5 KBRust Blame HistoryRaw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Rust's slice iterators are lazy and compose; a chain is resolved into one
// index loop, with each binding becoming an lvalue into the original container.
// That is what makes `*d = v` through `iter_mut()` write back to the caller's
// slice rather than to a copy.
fn main() {
    let v: Vec<i32> = vec![10, 20, 30, 40, 50];

    for x in v.iter() {
        print!("{} ", x);
    }
    println!("");

    for (i, x) in v.iter().enumerate() {
        print!("{}:{} ", i, x);
    }
    println!("");

    let w: Vec<i32> = vec![1, 2, 3];
    for (a, b) in v.iter().zip(w.iter()) {
        print!("{} ", a + b);
    }
    println!("");

    for c in v.chunks_exact(2) {
        print!("[{} {}] ", c[0], c[1]);
    }
    println!("");

    for c in v.windows(3) {
        print!("{} ", c[0] + c[1] + c[2]);
    }
    println!("");

    // Writing through iter_mut must reach the original.
    let mut m: Vec<i32> = vec![1, 2, 3, 4];
    for d in m.iter_mut() {
        *d = *d * 100;
    }
    println!("{:?}", m);

    // chunks_exact_mut, zipped against a read-only source.
    let src: Vec<i32> = vec![7, 8];
    let mut dst: Vec<i32> = vec![0, 0, 0, 0];
    for (s, c) in src.iter().zip(dst.chunks_exact_mut(2)) {
        c[0] = *s;
        c[1] = *s + 1;
    }
    println!("{:?}", dst);

    // zip stops at the shorter side, as Rust's does.
    let short: Vec<i32> = vec![1];
    let mut n: i32 = 0;
    for (_a, _b) in v.iter().zip(short.iter()) {
        n += 1;
    }
    println!("{}", n);
}