From 7efccc36b4c26c444eab2531b6139190af569d6f Mon Sep 17 00:00:00 2001 From: mo8it Date: Thu, 27 Jun 2024 13:24:21 +0200 Subject: [PATCH] lifetimes1 solution --- exercises/16_lifetimes/lifetimes1.rs | 18 ++++++++++++----- rustlings-macros/info.toml | 3 +-- solutions/16_lifetimes/lifetimes1.rs | 29 +++++++++++++++++++++++++++- 3 files changed, 42 insertions(+), 8 deletions(-) diff --git a/exercises/16_lifetimes/lifetimes1.rs b/exercises/16_lifetimes/lifetimes1.rs index d34f3abd..19e2d398 100644 --- a/exercises/16_lifetimes/lifetimes1.rs +++ b/exercises/16_lifetimes/lifetimes1.rs @@ -3,6 +3,7 @@ // going out of scope before it is used. Remember, references are borrows and do // not own their own data. What if their owner goes out of scope? +// TODO: Fix the compiler error by updating the function signature. fn longest(x: &str, y: &str) -> &str { if x.len() > y.len() { x @@ -12,9 +13,16 @@ fn longest(x: &str, y: &str) -> &str { } fn main() { - let string1 = String::from("abcd"); - let string2 = "xyz"; - - let result = longest(string1.as_str(), string2); - println!("The longest string is '{}'", result); + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_longest() { + assert_eq!(longest("abcd", "123"), "abcd"); + assert_eq!(longest("abc", "1234"), "1234"); + } } diff --git a/rustlings-macros/info.toml b/rustlings-macros/info.toml index bed2eafa..e2ebfa5c 100644 --- a/rustlings-macros/info.toml +++ b/rustlings-macros/info.toml @@ -821,9 +821,8 @@ You may need this: [[exercises]] name = "lifetimes1" dir = "16_lifetimes" -test = false hint = """ -Let the compiler guide you. Also take a look at the book if you need help: +Let the compiler guide you. Also take a look at The Book if you need help: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html""" [[exercises]] diff --git a/solutions/16_lifetimes/lifetimes1.rs b/solutions/16_lifetimes/lifetimes1.rs index 4e181989..ca7b688d 100644 --- a/solutions/16_lifetimes/lifetimes1.rs +++ b/solutions/16_lifetimes/lifetimes1.rs @@ -1 +1,28 @@ -// Solutions will be available before the stable release. Thank you for testing the beta version 🥰 +// The Rust compiler needs to know how to check whether supplied references are +// valid, so that it can let the programmer know if a reference is at risk of +// going out of scope before it is used. Remember, references are borrows and do +// not own their own data. What if their owner goes out of scope? + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + // ^^^^ ^^ ^^ ^^ + if x.len() > y.len() { + x + } else { + y + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_longest() { + assert_eq!(longest("abcd", "123"), "abcd"); + assert_eq!(longest("abc", "1234"), "1234"); + } +}