diff options
author | Jordan Gong <jordan.gong@protonmail.com> | 2020-09-03 15:26:30 +0800 |
---|---|---|
committer | Jordan Gong <jordan.gong@protonmail.com> | 2020-09-03 15:26:30 +0800 |
commit | f23a4fe4bcb7ae0b47d625f89abb281646ea33a7 (patch) | |
tree | a9bad1cd534d13d007472a9ea196f9f409504e85 /lifetimes/src/main.rs | |
parent | 638f6d997e76f45a665e2de741e6c4b2b5616aef (diff) |
Care about lifetimes
Diffstat (limited to 'lifetimes/src/main.rs')
-rw-r--r-- | lifetimes/src/main.rs | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/lifetimes/src/main.rs b/lifetimes/src/main.rs new file mode 100644 index 0000000..8dec31f --- /dev/null +++ b/lifetimes/src/main.rs @@ -0,0 +1,41 @@ +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} + +use std::fmt::Display; + +// generic type params, trait bound, and lifetimes +fn longest_with_an_announcement<'a, T>( + x: &'a str, + y: &'a str, + ann: T, +) -> &'a str +where + T: Display, +{ + println!("Announcement! {}", ann); + if x.len() > y.len() { + x + } else { + y + } +} + +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); + + let result = longest_with_an_announcement( + string1.as_str(), + string2, + "Today is someone's birthday!", + ); + println!("The longest string is {}", result); +} |