Skip to content

Commit ae87206

Browse files
committed
lifetimes
1 parent bbb2177 commit ae87206

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/main.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ fn main() {
99
basics::basics();
1010
println!();
1111
stuff::collections();
12-
stuff::error_handling();
12+
stuff::lifetimes();
1313
println!();
14+
stuff::error_handling();
1415
guessgame::guess_game();
1516
}

src/myutils/stuff.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use core::panic;
22
use std::{
3+
fmt::Display,
34
fs::File,
45
io::{ErrorKind, Read},
56
};
@@ -32,3 +33,26 @@ fn read_username_from_file() -> Result<String, std::io::Error> {
3233
File::open("hello.txt")?.read_to_string(&mut s)?;
3334
Ok(s)
3435
}
36+
37+
pub fn lifetimes() {
38+
let string1 = String::from("long string is long");
39+
{
40+
let string2 = String::from("xyz");
41+
let result = longest(string1.as_str(), string2.as_str());
42+
println!("lifetimes: the longest string is {}", result);
43+
44+
longest_with_announcement(string1.as_str(), string2.as_str(), "hoho!");
45+
}
46+
}
47+
48+
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
49+
if x.len() > y.len() { x } else { y }
50+
}
51+
52+
fn longest_with_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str
53+
where
54+
T: Display,
55+
{
56+
println!("Announcement! {}", ann);
57+
if x.len() > y.len() { x } else { y }
58+
}

0 commit comments

Comments
 (0)