nandi/rustnimpublic Fork 0
ae9f986fc43d0fc9ab029946e2c7a25cdc72b4ed
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.

023-slice-iterators.rs · 57 lines · 1.5 KBRust Blame HistoryRaw
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 16h ago1// Rust's slice iterators are lazy and compose; a chain is resolved into one
2// index loop, with each binding becoming an lvalue into the original container.
3// That is what makes `*d = v` through `iter_mut()` write back to the caller's
4// slice rather than to a copy.
5fn main() {
6 let v: Vec<i32> = vec![10, 20, 30, 40, 50];
7
8 for x in v.iter() {
9 print!("{} ", x);
10 }
11 println!("");
12
13 for (i, x) in v.iter().enumerate() {
14 print!("{}:{} ", i, x);
15 }
16 println!("");
17
18 let w: Vec<i32> = vec![1, 2, 3];
19 for (a, b) in v.iter().zip(w.iter()) {
20 print!("{} ", a + b);
21 }
22 println!("");
23
24 for c in v.chunks_exact(2) {
25 print!("[{} {}] ", c[0], c[1]);
26 }
27 println!("");
28
29 for c in v.windows(3) {
30 print!("{} ", c[0] + c[1] + c[2]);
31 }
32 println!("");
33
34 // Writing through iter_mut must reach the original.
35 let mut m: Vec<i32> = vec![1, 2, 3, 4];
36 for d in m.iter_mut() {
37 *d = *d * 100;
38 }
39 println!("{:?}", m);
40
41 // chunks_exact_mut, zipped against a read-only source.
42 let src: Vec<i32> = vec![7, 8];
43 let mut dst: Vec<i32> = vec![0, 0, 0, 0];
44 for (s, c) in src.iter().zip(dst.chunks_exact_mut(2)) {
45 c[0] = *s;
46 c[1] = *s + 1;
47 }
48 println!("{:?}", dst);
49
50 // zip stops at the shorter side, as Rust's does.
51 let short: Vec<i32> = vec![1];
52 let mut n: i32 = 0;
53 for (_a, _b) in v.iter().zip(short.iter()) {
54 n += 1;
55 }
56 println!("{}", n);
57}