From 13233d5eb18cf1322c5a84b15310d870c10f6483 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Thu, 7 Feb 2019 12:28:51 -0500 Subject: [PATCH] Add advanced_lifetimes example --- .idea/misc.xml | 1 + .idea/rust.iml | 5 ++ .idea/workspace.xml | 133 +++++++++++++++++++-------------- advanced_lifetimes/Cargo.toml | 7 ++ advanced_lifetimes/src/lib.rs | 26 +++++++ advanced_lifetimes/src/main.rs | 19 +++++ 6 files changed, 134 insertions(+), 57 deletions(-) create mode 100644 advanced_lifetimes/Cargo.toml create mode 100644 advanced_lifetimes/src/lib.rs create mode 100644 advanced_lifetimes/src/main.rs diff --git a/.idea/misc.xml b/.idea/misc.xml index 5fa0a85..fead741 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -37,6 +37,7 @@ + diff --git a/.idea/rust.iml b/.idea/rust.iml index 08adc04..32f1836 100644 --- a/.idea/rust.iml +++ b/.idea/rust.iml @@ -149,9 +149,14 @@ + + + + + diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 29a8446..24dcbe8 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,8 +2,6 @@ - - @@ -16,11 +14,28 @@ - - + + - - + + + + + + + + + + + + + + + + + + + @@ -54,8 +69,6 @@ @@ -138,12 +153,12 @@ - + - + @@ -177,7 +192,7 @@ - + @@ -205,7 +220,7 @@ - + - + - - @@ -266,11 +271,21 @@ + + @@ -283,21 +298,15 @@ + + + - - - - - - - - - @@ -322,6 +331,12 @@ + + + + + + @@ -344,7 +359,7 @@ - + @@ -358,24 +373,6 @@ - - - - - - - - - - - - - - - - - - @@ -791,8 +788,30 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/advanced_lifetimes/Cargo.toml b/advanced_lifetimes/Cargo.toml new file mode 100644 index 0000000..ac48674 --- /dev/null +++ b/advanced_lifetimes/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "advanced_lifetimes" +version = "0.1.0" +authors = ["Timothy Warren "] +edition = "2018" + +[dependencies] diff --git a/advanced_lifetimes/src/lib.rs b/advanced_lifetimes/src/lib.rs new file mode 100644 index 0000000..754f8f9 --- /dev/null +++ b/advanced_lifetimes/src/lib.rs @@ -0,0 +1,26 @@ +struct Context<'s>(&'s str); + +// 's : 'c tells Rust that the 's lifetime is tied to the 'c lifetime +struct Parser<'c, 's : 'c> { + context: &'c Context<'s>, +} + +impl<'c, 's> Parser<'c, 's> { + fn parse(&self) -> Result<(), &'s str> { + Err(&self.context.0[1..]) + } +} + +fn parse_context(context: Context) -> Result<(), &str> { + Parser { context: &context }.parse() +} + +struct Ref<'a, T: 'a>(&'a T); + +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + assert_eq!(2 + 2, 4); + } +} diff --git a/advanced_lifetimes/src/main.rs b/advanced_lifetimes/src/main.rs new file mode 100644 index 0000000..c8be1c2 --- /dev/null +++ b/advanced_lifetimes/src/main.rs @@ -0,0 +1,19 @@ +trait Red {} + +struct Ball<'a> { + diameter: &'a i32, +} + +impl<'a> Red for Ball<'a> {} + +struct StrWrap<'a>(&'a str); + +fn foo(string: &str) -> StrWrap<'_> { // Anonymous lifetime + StrWrap(string) +} + +fn main() { + let num = 5; + + let obj = Box::new(Ball { diameter: &num}) as Box; +}