From 5625678e5787f222d9a35c59da93a6f36cb6a322 Mon Sep 17 00:00:00 2001 From: Skarlett <360d@pm.me> Date: Fri, 11 Mar 2022 03:11:16 -0600 Subject: [PATCH] Add easy lifetime problems --- solutions/lifetime/lifetime.md | 66 ++++++++++++++++++++++++++++++++++ src/lifetime/basic.md | 66 +++++++++++++++++++++++++++++++++- 2 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 solutions/lifetime/lifetime.md diff --git a/solutions/lifetime/lifetime.md b/solutions/lifetime/lifetime.md new file mode 100644 index 0000000..68be366 --- /dev/null +++ b/solutions/lifetime/lifetime.md @@ -0,0 +1,66 @@ +# Lifetime + + +**Lifetimes** + +1. 🌟 +```rust,editable +/* Make it work */ + +#[derive(Debug)] +struct NoCopyType {} + +#[derive(Debug)] +struct Example<'a, 'b> { + a: &'a u32, + b: &'b NoCopyType +} + +fn main() +{ + /* 'a tied to fn-main stackframe */ + let var_a = 35; + let example: Example; + + // { + /* lifetime 'b tied to new stackframe/scope */ + let var_b = NoCopyType {}; + + /* fixme */ + example = Example { a: &var_a, b: &var_b }; + // } + + println!("(Success!) {:?}", example); +} +``` + + +2. 🌟 +```rust,editable + +#[derive(Debug)] +struct NoCopyType {} + +#[derive(Debug)] +#[allow(dead_code)] +struct Example<'a, 'b> { + a: &'a u32, + b: &'b NoCopyType +} + +/* Fix function signature */ +fn fix_me<'b>(foo: &Example<'b>) -> &'b NoCopyType +{ foo.b } + +fn main() +{ + let no_copy = NoCopyType {}; + let example = Example { a: &1, b: &no_copy }; + fix_me(&example); + print!("Success!") +} +``` + + + + diff --git a/src/lifetime/basic.md b/src/lifetime/basic.md index 40439f4..7c6dde2 100644 --- a/src/lifetime/basic.md +++ b/src/lifetime/basic.md @@ -23,4 +23,68 @@ fn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command // ex fn new(buf: &mut [u8]) -> BufWriter; // elided fn new(buf: &mut [u8]) -> BufWriter<'_>; // elided (with `rust_2018_idioms`) fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a> // expanded -``` \ No newline at end of file +``` + +**Lifetimes** + +1. 🌟 +```rust,editable +/* Make it work */ + +#[derive(Debug)] +struct NoCopyType {} + +#[derive(Debug)] +struct Example<'a, 'b> { + a: &'a u32, + b: &'b NoCopyType +} + +fn main() +{ + /* 'a tied to fn-main stackframe */ + let var_a = 35; + let example: Example; + + { + /* lifetime 'b tied to new stackframe/scope */ + let var_b = NoCopyType {}; + + /* fixme */ + example = Example { a: &var_a, b: &var_b }; + } + + println!("(Success!) {:?}", example); +} +``` + + +2. 🌟 +```rust,editable + +#[derive(Debug)] +struct NoCopyType {} + +#[derive(Debug)] +#[allow(dead_code)] +struct Example<'a, 'b> { + a: &'a u32, + b: &'b NoCopyType +} + +/* Fix function signature */ +fn fix_me(foo: &Example) -> &NoCopyType +{ foo.b } + +fn main() +{ + let no_copy = NoCopyType {}; + let example = Example { a: &1, b: &no_copy }; + fix_me(&example); + print!("Success!") +} +``` + + + +