Skip to content

Commit 6b2db67

Browse files
committed
added demos, shuflr example
1 parent a682663 commit 6b2db67

File tree

6 files changed

+56
-0
lines changed

6 files changed

+56
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,6 @@ in a controlled repository now.
5959
* `lifetimes-example.rs`: example involving Rust lifetimes
6060
* `strref.rs`: example involving Rust string clones and copies
6161
* `closures/`: closure examples
62+
* `for-demo.rs`: example of passing iterators
63+
* `iter-from-fn.rs`: example use of `iter::from_fn()`
64+
* `rev.rs`: example `for` loop with reversed iterator

for-demo.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
pub fn count<T, E>(values: T)
2+
where T: IntoIterator<Item=E>, E: std::fmt::Debug
3+
{
4+
let mut iter = values.into_iter();
5+
while let Some(i) = iter.next() {
6+
println!("{i:?}");
7+
}
8+
}
9+
10+
fn main() {
11+
count(1..=5);
12+
count('a'..='c');
13+
count(["hello", "world"]);
14+
let v = vec![(1, 2), (3, 4)];
15+
count(v.iter());
16+
count(v.iter());
17+
}

iter-from-fn.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
fn main() {
2+
let mut c = 'a';
3+
let iter = std::iter::from_fn(|| {
4+
if c >= 'e' {
5+
return None;
6+
}
7+
let result = c;
8+
c = std::char::from_u32(c as u32 + 1).unwrap();
9+
Some(result)
10+
});
11+
let xs: String = iter.collect();
12+
println!("{xs}");
13+
}

rev.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn main() {
2+
for i in 0..3 {
3+
println!("{i}");
4+
}
5+
for i in (0..3).rev() {
6+
println!("{i}");
7+
}
8+
}

shuflr/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,7 @@ rand = "0.8.3"
1212
[lib]
1313
name = "shuflr"
1414
path = "shuflr.rs"
15+
16+
[[example]]
17+
name = "demo"
18+
path = "demo.rs"

shuflr/demo.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
use shuflr::*;
2+
use rand::thread_rng;
3+
4+
fn main() {
5+
let v: Vec<char> = ('a'..='z').collect();
6+
let s: String = v
7+
.shuffled(&mut thread_rng())
8+
.flat_map(|c| c.to_uppercase())
9+
.collect();
10+
println!("{s}");
11+
}

0 commit comments

Comments
 (0)