Skip to content

Commit 5cf4cf1

Browse files
committed
added lifetimes example
1 parent bbba6b3 commit 5cf4cf1

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,4 @@ in a controlled repository now.
5656
* `enum-example.rs`: example of Rust enum
5757
* `closure-example.rs`: example of Rust closure
5858
* `iterator-example.rs`: example of Rust iterator
59+
* `lifetimes-example.rs`: example involving Rust lifetimes

lifetimes-example.rs

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
struct Halves<'a, 'b, T> {
2+
first: &'a [T],
3+
last: &'b [T],
4+
}
5+
6+
/*
7+
fn half<'a, T>(source: &'a [T]) -> Halves<'a, 'a, T> {
8+
let halfway = source.len() / 2;
9+
Halves {
10+
first: &source[..halfway],
11+
last: &source[halfway..],
12+
}
13+
}
14+
*/
15+
16+
fn swap<'a, 'b, T>(source: Halves<'a, 'b, T>) -> Halves<'b, 'a, T> {
17+
Halves {
18+
first: source.last,
19+
last: source.first,
20+
}
21+
}
22+
23+
/*
24+
fn longer(s: String, t: String) -> String {
25+
if s.len() >= t.len() {
26+
s
27+
} else {
28+
t
29+
}
30+
}
31+
*/
32+
33+
fn main() {
34+
// let halves = half(&[1, 2, 3, 4, 5]);
35+
let first = vec![1, 2];
36+
let last = vec![3, 4, 5];
37+
let halves = Halves { first: &first, last: &last };
38+
let swapped = swap(halves);
39+
let new_first = swapped.first;
40+
drop(swapped);
41+
//drop(first);
42+
println!("{:?}", new_first);
43+
}

0 commit comments

Comments
 (0)