Compare commits

...
8 Commits
Author SHA1 Message Date
AramJonghu 50f23f7e48 feat: progress iterators 2026-09-13 18:23:25 +02:00
AramJonghu 88b981b50c feat: progress iterators 2026-09-13 02:04:29 +02:00
AramJonghu 5c1324aae8 feat: completed tests 2026-09-13 01:13:24 +02:00
AramJonghu c7f0365fec feat: completed lifetimes 2026-09-13 01:13:13 +02:00
AramJonghu 3f32906547 feat: quiz3 done of traits and generics 2026-09-11 17:38:14 +02:00
AramJonghu 8ded4cc8b5 feat: traits done 2026-09-11 17:37:48 +02:00
AramJonghu b94cdfd4c4 feat: generics done 2026-09-11 17:37:16 +02:00
AramJonghu fe01747f82 feat(errors): completed errors 2026-09-06 22:26:34 +02:00
24 changed files with 79 additions and 41 deletions
+3 -3
View File
@@ -4,12 +4,12 @@
// construct to `Option` that can be used to express error conditions. Change
// the function signature and body to return `Result<String, String>` instead
// of `Option<String>`.
fn generate_nametag_text(name: String) -> Option<String> {
fn generate_nametag_text(name: String) -> Result<String, String> {
if name.is_empty() {
// Empty names aren't allowed
None
Err("Empty names aren't allowed".to_string())
} else {
Some(format!("Hi! My name is {name}"))
Ok(format!("Hi! My name is {name}"))
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let cost_per_item = 5;
// TODO: Handle the error case as described above.
let qty = item_quantity.parse::<i32>();
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)
}
+3 -1
View File
@@ -15,7 +15,7 @@ fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
// TODO: Fix the compiler error by changing the signature and body of the
// `main` function.
fn main() {
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut tokens = 100;
let pretend_user_input = "8";
@@ -24,8 +24,10 @@ fn main() {
if cost > tokens {
println!("You can't afford that many!");
Ok(())
} else {
tokens -= cost;
println!("You now have {tokens} tokens.");
Ok(())
}
}
+7 -1
View File
@@ -1,3 +1,5 @@
use std::cmp::Ordering;
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
@@ -11,7 +13,11 @@ impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<Self, CreationError> {
// TODO: This function shouldn't always return an `Ok`.
// Read the tests below to clarify what should be returned.
Ok(Self(value as u64))
match value.cmp(&0) {
Ordering::Less => Err(CreationError::Negative),
Ordering::Equal => Err(CreationError::Zero),
Ordering::Greater => Ok(Self(value as u64)),
}
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ impl PositiveNonzeroInteger {
// TODO: Add the correct return type `Result<(), Box<dyn ???>>`. What can we
// use to describe both errors? Is there a trait which both errors implement?
fn main() {
fn main() -> Result<(), Box<dyn Error>> {
let pretend_user_input = "42";
let x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
+1 -1
View File
@@ -34,7 +34,7 @@ impl PositiveNonzeroInteger {
fn parse(s: &str) -> Result<Self, ParsePosNonzeroError> {
// TODO: change this to return an appropriate error instead of panicking
// when `parse()` returns an error.
let x: i64 = s.parse().unwrap();
let x: i64 = s.parse().map_err(ParsePosNonzeroError::ParseInt)?;
Self::new(x).map_err(ParsePosNonzeroError::Creation)
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ fn main() {
// TODO: Fix the compiler error by annotating the type of the vector
// `Vec<T>`. Choose `T` as some integer type that can be created from
// `u8` and `i8`.
let mut numbers = Vec::new();
let mut numbers: Vec<i16> = Vec::new();
// Don't change the lines below.
let n1: u8 = 42;
+4 -4
View File
@@ -1,12 +1,12 @@
// This powerful wrapper provides the ability to store a positive integer value.
// TODO: Rewrite it using a generic so that it supports wrapping ANY type.
struct Wrapper {
value: u32,
struct Wrapper<T> {
value: T,
}
// TODO: Adapt the struct's implementation to be generic over the wrapped value.
impl Wrapper {
fn new(value: u32) -> Self {
impl<T> Wrapper<T> {
fn new(value: T) -> Self {
Wrapper { value }
}
}
+3
View File
@@ -6,6 +6,9 @@ trait AppendBar {
impl AppendBar for String {
// TODO: Implement `AppendBar` for the type `String`.
fn append_bar(self) -> Self {
self + &String::from("Bar")
}
}
fn main() {
+6
View File
@@ -4,6 +4,12 @@ trait AppendBar {
// TODO: Implement the trait `AppendBar` for a vector of strings.
// `append_bar` should push the string "Bar" into the vector.
impl AppendBar for Vec<String> {
fn append_bar(mut self) -> Self {
self.push(String::from("Bar"));
self
}
}
fn main() {
// You can optionally experiment here.
+3 -1
View File
@@ -3,7 +3,9 @@ trait Licensed {
// implementors like the two structs below can share that default behavior
// without repeating the function.
// The default license information should be the string "Default license".
fn licensing_info(&self) -> String;
fn licensing_info(&self) -> String {
String::from("Default license")
}
}
struct SomeSoftware {
+1 -1
View File
@@ -11,7 +11,7 @@ impl Licensed for SomeSoftware {}
impl Licensed for OtherSoftware {}
// TODO: Fix the compiler error by only changing the signature of this function.
fn compare_license_types(software1: ???, software2: ???) -> bool {
fn compare_license_types(software1: impl Licensed, software2: impl Licensed) -> bool {
software1.licensing_info() == software2.licensing_info()
}
+1 -1
View File
@@ -19,7 +19,7 @@ impl SomeTrait for OtherStruct {}
impl OtherTrait for OtherStruct {}
// TODO: Fix the compiler error by only changing the signature of this function.
fn some_func(item: ???) -> bool {
fn some_func(item: impl SomeTrait + OtherTrait) -> bool {
item.some_function() && item.other_function()
}
+1 -1
View File
@@ -4,7 +4,7 @@
// 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 {
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
+1 -1
View File
@@ -15,6 +15,6 @@ fn main() {
{
let string2 = String::from("xyz");
result = longest(&string1, &string2);
}
println!("The longest string is '{result}'");
}
}
+3 -3
View File
@@ -1,9 +1,9 @@
// Lifetimes are also needed when structs hold references.
// TODO: Fix the compiler errors about the struct.
struct Book {
author: &str,
title: &str,
struct Book<'a> {
author: &'a str,
title: &'a str,
}
fn main() {
+3 -2
View File
@@ -13,11 +13,12 @@ fn main() {
mod tests {
// TODO: Import `is_even`. You can use a wildcard to import everything in
// the outer module.
use super::*;
#[test]
fn you_can_assert() {
// TODO: Test the function `is_even` with some values.
assert!();
assert!();
assert!(!is_even(1));
assert!(is_even(12));
}
}
+4 -4
View File
@@ -15,9 +15,9 @@ mod tests {
#[test]
fn you_can_assert_eq() {
// TODO: Test the function `power_of_2` with some values.
assert_eq!();
assert_eq!();
assert_eq!();
assert_eq!();
assert_eq!(power_of_2(2), 4);
assert_eq!(power_of_2(3), 8);
assert_eq!(power_of_2(10), 1024);
assert_eq!(power_of_2(42), 4398046511104);
}
}
+4 -2
View File
@@ -29,13 +29,14 @@ mod tests {
// TODO: This test should check if the rectangle has the size that we
// pass to its constructor.
let rect = Rectangle::new(10, 20);
assert_eq!(todo!(), 10); // Check width
assert_eq!(todo!(), 20); // Check height
assert_eq!(rect.width, 10); // Check width
assert_eq!(rect.height, 20); // Check height
}
// TODO: This test should check if the program panics when we try to create
// a rectangle with negative width.
#[test]
#[should_panic]
fn negative_width() {
let _rect = Rectangle::new(-10, 10);
}
@@ -43,6 +44,7 @@ mod tests {
// TODO: This test should check if the program panics when we try to create
// a rectangle with negative height.
#[test]
#[should_panic]
fn negative_height() {
let _rect = Rectangle::new(10, -10);
}
+4 -4
View File
@@ -13,13 +13,13 @@ mod tests {
let my_fav_fruits = &["banana", "custard apple", "avocado", "peach", "raspberry"];
// TODO: Create an iterator over the slice.
let mut fav_fruits_iterator = todo!();
let mut fav_fruits_iterator = my_fav_fruits.iter();
assert_eq!(fav_fruits_iterator.next(), Some(&"banana"));
assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()`
assert_eq!(fav_fruits_iterator.next(), Some(&"custard apple")); // TODO: Replace `todo!()`
assert_eq!(fav_fruits_iterator.next(), Some(&"avocado"));
assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()`
assert_eq!(fav_fruits_iterator.next(), Some(&"peach")); // TODO: Replace `todo!()`
assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry"));
assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()`
assert_eq!(fav_fruits_iterator.next(), None); // TODO: Replace `todo!()`
}
}
+5 -1
View File
@@ -1,13 +1,15 @@
// In this exercise, you'll learn some of the unique advantages that iterators
// can offer.
// I failed.
// TODO: Complete the `capitalize_first` function.
// "hello" -> "Hello"
fn capitalize_first(input: &str) -> String {
let mut chars = input.chars();
match chars.next() {
None => String::new(),
Some(first) => todo!(),
Some(first) => first.to_uppercase().to_string() + chars.as_str(),
}
}
@@ -16,6 +18,7 @@ fn capitalize_first(input: &str) -> String {
// ["hello", "world"] -> ["Hello", "World"]
fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
// ???
words.iter().map(|word| capitalize_first(word)).collect()
}
// TODO: Apply the `capitalize_first` function again to a slice of string
@@ -23,6 +26,7 @@ fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
// ["hello", " ", "world"] -> "Hello World"
fn capitalize_words_string(words: &[&str]) -> String {
// ???
words.iter().map(|word| capitalize_first(word)).collect()
}
fn main() {
+13 -3
View File
@@ -11,21 +11,31 @@ enum DivisionError {
// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error.
fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
todo!();
if b == 0 {
Err(DivisionError::DivideByZero)
} else if b == -1 && a == i64::MIN {
Err(DivisionError::IntegerOverflow)
} else if a % b == 0 {
Ok(a / b)
} else {
Err(DivisionError::NotDivisible)
}
}
// TODO: Add the correct return type and complete the function body.
// Desired output: `Ok([1, 11, 1426, 3])`
fn result_with_list() {
fn result_with_list() -> Result<Vec<i64>, DivisionError> {
let numbers = [27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));
division_results.collect()
}
// TODO: Add the correct return type and complete the function body.
// Desired output: `[Ok(1), Ok(11), Ok(1426), Ok(3)]`
fn list_of_results() {
fn list_of_results() -> Vec<Result<i64, DivisionError>> {
let numbers = [27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));
division_results.collect()
}
fn main() {
+2
View File
@@ -10,6 +10,8 @@ fn factorial(num: u64) -> u64 {
// - additional variables
// For an extra challenge, don't use:
// - recursion
(1..=num).product()
}
fn main() {
+4 -4
View File
@@ -12,18 +12,18 @@
// block to support alphabetical report cards in addition to numerical ones.
// TODO: Adjust the struct as described above.
struct ReportCard {
grade: f32,
struct ReportCard<T> {
grade: T,
student_name: String,
student_age: u8,
}
// TODO: Adjust the impl block as described above.
impl ReportCard {
impl<T: std::fmt::Display> ReportCard<T> {
fn print(&self) -> String {
format!(
"{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade,
self.student_name, self.student_age, self.grade,
)
}
}