Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9b8b363

Browse files
fivonacci
1 parent 1daabc3 commit 9b8b363

File tree

2 files changed

+96
-1
lines changed

2 files changed

+96
-1
lines changed

‎examples/closures.rs

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,48 @@
11

2+
fn apply<F>(x: f64, f: F) -> f64
3+
where F: Fn(f64) -> f64 {
4+
f(x)
5+
}
6+
7+
fn mutate<F> (mut f: F)
8+
where F: FnMut() {
9+
f()
10+
}
11+
212
fn main() {
313
let f = |x| x*x;
414
let res = f(10);
5-
println!("res {}", res);
15+
println!("res {}", f(1));
16+
17+
let a = 2.0;
18+
let b = 1.0;
19+
let f1 = |x| a*x + b;
20+
println!("res is {}", f1(2.0));
21+
22+
let res1 = apply(3.0, f1);
23+
let res2 = apply(3.14, |x| x.sin());
24+
println!("res1 {} res2 {}", res1, res2);
25+
26+
let mut s = "world";
27+
mutate(|| s = "hello");
28+
println!("s is {}", s);
29+
assert_eq!(s, "hello");
30+
31+
let mut s = "world";
32+
let mut changer = || s = "hello";
33+
changer();
34+
35+
assert_eq!(s, "hello");
36+
println!("{}", s);
37+
38+
let name = "dolly".to_string();
39+
let age = 42;
40+
41+
let c_name = name.clone();
42+
let c = move || {
43+
println!("name is {} age is {}", c_name, age);
44+
};
45+
c();
46+
47+
println!("{}", name);
648
}

‎examples/fivonacci.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
#[derive(Debug)]
3+
struct Fivo {
4+
first: u32,
5+
second: u32
6+
}
7+
8+
impl Iterator for Fivo {
9+
type Item = u32;
10+
fn next(&mut self) -> Option<Self::Item> {
11+
let res = self.first + self.second;
12+
self.first = self.second;
13+
self.second = res;
14+
15+
if res > 1000 {
16+
None
17+
} else {
18+
Some(res)
19+
}
20+
}
21+
}
22+
23+
#[derive(Debug)]
24+
struct StrFivo {
25+
first: String,
26+
second: String
27+
}
28+
29+
impl Iterator for StrFivo {
30+
type Item = String;
31+
fn next(&mut self) -> Option<Self::Item> {
32+
let res = self.first.to_string() + &self.second;
33+
self.first = self.second.to_string();
34+
self.second = res.to_string();
35+
if res.len() > 200 {
36+
None
37+
} else {
38+
Some(res.to_string())
39+
}
40+
}
41+
}
42+
43+
fn main() {
44+
let fivonachi_iter = || Fivo { first: 1, second: 2};
45+
for i in fivonachi_iter() {
46+
println!("{}", i);
47+
}
48+
49+
let fivostr_iter = |a: &str, b: &str| StrFivo { first: a.to_string(), second: b.to_string() } ;
50+
for s in fivostr_iter("he", "wo") {
51+
println!("{}", s);
52+
}
53+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /