From 65f88596cba53e710b0435bea488462719a1c55b Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Thu, 31 Jan 2019 14:00:49 -0500 Subject: [PATCH] Add lifetime generic example --- .idea/misc.xml | 1 + .idea/rust.iml | 5 +++ .idea/workspace.xml | 94 ++++++++++++++++++------------------------- lifetimes/Cargo.toml | 7 ++++ lifetimes/src/main.rs | 57 ++++++++++++++++++++++++++ 5 files changed, 109 insertions(+), 55 deletions(-) create mode 100644 lifetimes/Cargo.toml create mode 100644 lifetimes/src/main.rs diff --git a/.idea/misc.xml b/.idea/misc.xml index 92170b1..c897734 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -18,6 +18,7 @@ + diff --git a/.idea/rust.iml b/.idea/rust.iml index 454cb85..d704567 100644 --- a/.idea/rust.iml +++ b/.idea/rust.iml @@ -70,6 +70,10 @@ + + + + @@ -78,6 +82,7 @@ + diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 5bf83ff..450a7a3 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -14,42 +14,14 @@ - - - - - - - - - - - - - - - - - - - - - - - - - + - - + + + - - - - - @@ -104,6 +76,7 @@ @@ -137,12 +110,12 @@ - + - + @@ -176,7 +149,7 @@ - + @@ -204,7 +177,7 @@ - + - - + + + - @@ -510,6 +483,21 @@ + + + + + + + + + + + + + + + @@ -530,17 +518,13 @@ - + - - + + + - - - - - diff --git a/lifetimes/Cargo.toml b/lifetimes/Cargo.toml new file mode 100644 index 0000000..f219582 --- /dev/null +++ b/lifetimes/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lifetimes" +version = "0.1.0" +authors = ["Timothy Warren "] +edition = "2018" + +[dependencies] diff --git a/lifetimes/src/main.rs b/lifetimes/src/main.rs new file mode 100644 index 0000000..2814dd9 --- /dev/null +++ b/lifetimes/src/main.rs @@ -0,0 +1,57 @@ +use std::fmt::Display; + +struct ImportantExcerpt<'a> { + part: &'a str, +} + +impl<'a> ImportantExcerpt<'a> { + fn level(&self) -> i32 { + 3 + } + + 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 result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); + + let string1 = String::from("long string is long"); + + { + let string2 = String::from("xyz"); + let result = longest(string1.as_str(), string2.as_str()); + println!("The longest string is {}", result); + } + + let novel = String::from("Call me Ishmael. Some years ago..."); + let first_sentence = novel.split('.') + .next() + .expect("Could not find a '.'"); + let _i = ImportantExcerpt { part: first_sentence }; +} + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} + +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 + } +}