From d6e49c8ae7556a81757e138eb13e5381e1e261e6 Mon Sep 17 00:00:00 2001 From: laurens Date: Sun, 6 Sep 2020 17:47:18 +0200 Subject: [PATCH] Add lifetimes example --- lifetimes/Cargo.toml | 9 +++++++++ lifetimes/src/main.rs | 47 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 lifetimes/Cargo.toml create mode 100644 lifetimes/src/main.rs diff --git a/lifetimes/Cargo.toml b/lifetimes/Cargo.toml new file mode 100644 index 0000000..a21aad1 --- /dev/null +++ b/lifetimes/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "lifetimes" +version = "0.1.0" +authors = ["laurens "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/lifetimes/src/main.rs b/lifetimes/src/main.rs new file mode 100644 index 0000000..495e038 --- /dev/null +++ b/lifetimes/src/main.rs @@ -0,0 +1,47 @@ +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} + +// No need to specify lifetime of second param since it is not used in the function +fn longest_always_first_param<'a>(x: &'a str, _y: &str) -> &'a str { + x +} + +#[derive(Debug)] +struct Excerpt<'a> { + part: &'a str, +} + +impl<'a> Excerpt<'a> { + // Because of the lifetime elision rules, no need to add lifetimes here, compiler is smart enough to figure it out + fn announce_and_return_part(&self, announcement: &str) -> &str { + println!("Attention please: {}", announcement); + self.part + } +} + +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + let _s: &'static str = "I have a static lifetime and will live until the program ends."; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); + println!( + "The longest string is maybe {}?", + longest_always_first_param(string1.as_str(), string2) + ); + + let novel = String::from("Call me Ishmael. Some years ago ..."); + let first_sentence = novel.split('.').next().expect("Could not find a '.'"); + let i = Excerpt { + part: first_sentence, + }; + + println!("excerpt: {:?}", i); + i.announce_and_return_part("hello"); +}