Skip to content

Commit d9d8b82

Browse files
committed
episode 15
1 parent cb303c1 commit d9d8b82

File tree

4 files changed

+69
-1
lines changed

4 files changed

+69
-1
lines changed

Cargo.lock

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
[workspace]
2-
members = ["./ownership-and-borrowing", "options-and-results", "errors", "iterators", "strings", "boxing", "conversions"]
2+
members = ["./ownership-and-borrowing", "options-and-results", "errors", "iterators", "strings", "boxing", "conversions", "closures"]

closures/Cargo.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[package]
2+
name = "closures"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]

closures/src/main.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#![allow(dead_code)]
2+
3+
use std::ops::AddAssign;
4+
5+
fn main() {
6+
println!("{:?}", map("a", |v| v));
7+
println!("{:?}", map(4, |v| v + 1));
8+
fn add_one(v: u32) -> u32 {
9+
v + 1
10+
}
11+
println!("{:?}", map(4, add_one));
12+
println!(
13+
"{:?}",
14+
map("a".to_string(), |mut v| {
15+
v.push_str("hello");
16+
v
17+
})
18+
);
19+
20+
let mut count = 0;
21+
println!(
22+
"{:?}",
23+
map("a".to_string(), move |mut v| {
24+
count += 1;
25+
v.push_str("hello");
26+
v
27+
})
28+
);
29+
dbg!(count);
30+
31+
struct Closure<'a> {
32+
count: &'a mut u32,
33+
}
34+
impl<'a> Closure<'a> {
35+
fn call(&mut self) -> u32 {
36+
self.count.add_assign(1);
37+
*self.count
38+
}
39+
}
40+
}
41+
struct Iter<F> {
42+
map: F,
43+
}
44+
45+
impl<F> Iter<F>
46+
where
47+
F: FnMut(u32) -> u32,
48+
{
49+
fn next(&mut self) -> u32 {
50+
(self.map)(42)
51+
}
52+
}
53+
fn map<T>(item: T, mut f: impl FnMut(T) -> T) -> T {
54+
let t = f(item);
55+
f(t)
56+
}

0 commit comments

Comments
 (0)