finish until lifetimes

This commit is contained in:
Samuele Iacoponi
2026-02-27 17:15:07 +01:00
parent b1b81f7e07
commit 8c99d4187d
9 changed files with 148 additions and 23 deletions

View File

@@ -1,6 +1,6 @@
DON'T EDIT THIS FILE! DON'T EDIT THIS FILE!
quiz3 tests1
intro1 intro1
intro2 intro2
@@ -64,4 +64,8 @@ traits1
traits2 traits2
traits3 traits3
traits4 traits4
traits5 traits5
quiz3
lifetimes1
lifetimes2
lifetimes3

View File

@@ -4,7 +4,7 @@
// not own their own data. What if their owner goes out of scope? // not own their own data. What if their owner goes out of scope?
// TODO: Fix the compiler error by updating the function signature. // TODO: Fix the compiler error by updating the function signature.
fn longest(x: &str, y: &str) -> &str { fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { if x.len() > y.len() {
x x
} else { } else {

View File

@@ -15,6 +15,6 @@ fn main() {
{ {
let string2 = String::from("xyz"); let string2 = String::from("xyz");
result = longest(&string1, &string2); result = longest(&string1, &string2);
println!("The longest string is '{result}'");
} }
println!("The longest string is '{result}'");
} }

View File

@@ -1,11 +1,12 @@
// Lifetimes are also needed when structs hold references. // Lifetimes are also needed when structs hold references.
// TODO: Fix the compiler errors about the struct. // TODO: Fix the compiler errors about the struct.
struct Book { struct Book<'a> {
author: &str, author: &'a str,
title: &str, title: &'a str,
} }
// Will the strings pointed to by book still be valid?
fn main() { fn main() {
let book = Book { let book = Book {
author: "George Orwell", author: "George Orwell",

View File

@@ -12,18 +12,18 @@
// block to support alphabetical report cards in addition to numerical ones. // block to support alphabetical report cards in addition to numerical ones.
// TODO: Adjust the struct as described above. // TODO: Adjust the struct as described above.
struct ReportCard { struct ReportCard<T> {
grade: f32, grade: T,
student_name: String, student_name: String,
student_age: u8, student_age: u8,
} }
// TODO: Adjust the impl block as described above. // TODO: Adjust the impl block as described above.
impl ReportCard { impl<T: std::fmt::Display> ReportCard<T> {
fn print(&self) -> String { fn print(&self) -> String {
format!( format!(
"{} ({}) - achieved a grade of {}", "{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade, &self.student_name, &self.student_age, &self.grade
) )
} }
} }

View File

@@ -1,4 +1,24 @@
fn main() { // The Rust compiler needs to know how to check whether supplied references are
// DON'T EDIT THIS SOLUTION FILE! // valid, so that it can let the programmer know if a reference is at risk of
// It will be automatically filled after you finish the exercise. // 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");
}
} }

View File

@@ -1,4 +1,29 @@
fn main() { fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
// DON'T EDIT THIS SOLUTION FILE! if x.len() > y.len() { x } else { y }
// It will be automatically filled after you finish the exercise. }
fn main() {
let string1 = String::from("long string is long");
// Solution1: You can move `strings2` out of the inner block so that it is
// not dropped before the print statement.
let string2 = String::from("xyz");
let result;
{
result = longest(&string1, &string2);
}
println!("The longest string is '{result}'");
// `string2` dropped at the end of the function.
// =========================================================================
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(&string1, &string2);
// Solution2: You can move the print statement into the inner block so
// that it is executed before `string2` is dropped.
println!("The longest string is '{result}'");
// `string2` dropped here (end of the inner scope).
}
} }

View File

@@ -1,4 +1,18 @@
fn main() { // Lifetimes are also needed when structs hold references.
// DON'T EDIT THIS SOLUTION FILE!
// It will be automatically filled after you finish the exercise. struct Book<'a> {
// ^^^^ added a lifetime annotation
author: &'a str,
// ^^
title: &'a str,
// ^^
}
fn main() {
let book = Book {
author: "George Orwell",
title: "1984",
};
println!("{} by {}", book.title, book.author);
} }

View File

@@ -1,4 +1,65 @@
fn main() { // An imaginary magical school has a new report card generation system written
// DON'T EDIT THIS SOLUTION FILE! // in Rust! Currently, the system only supports creating report cards where the
// It will be automatically filled after you finish the exercise. // student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the
// school also issues alphabetical grades (A+ -> F-) and needs to be able to
// print both types of report card!
//
// Make the necessary code changes in the struct `ReportCard` and the impl
// block to support alphabetical report cards in addition to numerical ones.
use std::fmt::Display;
// Make the struct generic over `T`.
struct ReportCard<T> {
// ^^^
grade: T,
// ^
student_name: String,
student_age: u8,
}
// To be able to print the grade, it has to implement the `Display` trait.
impl<T: Display> ReportCard<T> {
// ^^^^^^^ require that `T` implements `Display`.
fn print(&self) -> String {
format!(
"{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade,
)
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generate_numeric_report_card() {
let report_card = ReportCard {
grade: 2.1,
student_name: "Tom Wriggle".to_string(),
student_age: 12,
};
assert_eq!(
report_card.print(),
"Tom Wriggle (12) - achieved a grade of 2.1",
);
}
#[test]
fn generate_alphabetic_report_card() {
let report_card = ReportCard {
grade: "A+",
student_name: "Gary Plotter".to_string(),
student_age: 11,
};
assert_eq!(
report_card.print(),
"Gary Plotter (11) - achieved a grade of A+",
);
}
} }