some more progress

This commit is contained in:
2024-10-29 11:28:19 +01:00
parent f022d5c2bb
commit 0666f77c42
66 changed files with 1484 additions and 144 deletions

View File

@@ -4,6 +4,7 @@ fn array_and_vec() -> ([i32; 4], Vec<i32>) {
// TODO: Create a vector called `v` which contains the exact same elements as in the array `a`.
// Use the vector macro.
// let v = ???;
let v : Vec<i32> = vec![a[0], a[1], a[2], a[3]];
(a, v)
}

View File

@@ -4,6 +4,8 @@ fn vec_loop(input: &[i32]) -> Vec<i32> {
for element in input {
// TODO: Multiply each element in the `input` slice by 2 and push it to
// the `output` vector.
output.push(element * 2);
}
output
@@ -24,7 +26,7 @@ fn vec_map(input: &[i32]) -> Vec<i32> {
input
.iter()
.map(|element| {
// ???
element * 2
})
.collect()
}

View File

@@ -1,6 +1,6 @@
// TODO: Fix the compiler error in this function.
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let vec = vec;
let mut vec = vec;
vec.push(88);

View File

@@ -20,7 +20,7 @@ mod tests {
fn move_semantics2() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
let vec1 = fill_vec(vec0.clone());
assert_eq!(vec0, [22, 44, 66]);
assert_eq!(vec1, [22, 44, 66, 88]);

View File

@@ -1,5 +1,5 @@
// TODO: Fix the compiler error in the function without adding any new line.
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
vec.push(88);
vec

View File

@@ -10,8 +10,8 @@ mod tests {
fn move_semantics4() {
let mut x = Vec::new();
let y = &mut x;
let z = &mut x;
y.push(42);
let z = &mut x;
z.push(13);
assert_eq!(x, [42, 13]);
}

View File

@@ -4,12 +4,12 @@
// removing references (the character `&`).
// Shouldn't take ownership
fn get_char(data: String) -> char {
fn get_char(data: &String) -> char {
data.chars().last().unwrap()
}
// Should take ownership
fn string_uppercase(mut data: &String) {
fn string_uppercase(mut data: String) {
data = data.to_uppercase();
println!("{data}");
@@ -18,7 +18,7 @@ fn string_uppercase(mut data: &String) {
fn main() {
let data = "Rust is great!".to_string();
get_char(data);
get_char(&data);
string_uppercase(&data);
string_uppercase(data);
}

View File

@@ -1,9 +1,12 @@
struct ColorRegularStruct {
// TODO: Add the fields that the test `regular_structs` expects.
// What types should the fields have? What are the minimum and maximum values for RGB colors?
red: u8,
green: u8,
blue: u8
}
struct ColorTupleStruct(/* TODO: Add the fields that the test `tuple_structs` expects */);
struct ColorTupleStruct(/* TODO: Add the fields that the test `tuple_structs` expects */u8, u8, u8);
#[derive(Debug)]
struct UnitStruct;
@@ -20,6 +23,7 @@ mod tests {
fn regular_structs() {
// TODO: Instantiate a regular struct.
// let green =
let green = ColorRegularStruct { red: 0, green: 255, blue: 0 };
assert_eq!(green.red, 0);
assert_eq!(green.green, 255);
@@ -30,6 +34,7 @@ mod tests {
fn tuple_structs() {
// TODO: Instantiate a tuple struct.
// let green =
let green = ColorTupleStruct(0, 255, 0);
assert_eq!(green.0, 0);
assert_eq!(green.1, 255);
@@ -40,6 +45,7 @@ mod tests {
fn unit_structs() {
// TODO: Instantiate a unit struct.
// let unit_struct =
let unit_struct = UnitStruct;
let message = format!("{unit_struct:?}s are fun!");
assert_eq!(message, "UnitStructs are fun!");

View File

@@ -35,6 +35,11 @@ mod tests {
// TODO: Create your own order using the update syntax and template above!
// let your_order =
let your_order = Order {
name: String::from("Hacker in Rust"),
count: 1,
..order_template
};
assert_eq!(your_order.name, "Hacker in Rust");
assert_eq!(your_order.year, order_template.year);

View File

@@ -24,19 +24,30 @@ impl Package {
}
// TODO: Add the correct return type to the function signature.
fn is_international(&self) {
fn is_international(&self) -> bool {
// TODO: Read the tests that use this method to find out when a package
// is considered international.
self.sender_country != self.recipient_country
}
// TODO: Add the correct return type to the function signature.
fn get_fees(&self, cents_per_gram: u32) {
fn get_fees(&self, cents_per_gram: u32) -> u32 {
// TODO: Calculate the package's fees.
self.weight_in_grams * cents_per_gram
}
}
fn main() {
// You can optionally experiment here.
let ding = Package::new(String::from("NL"), String::from("DK"), 10);
if ding.is_international()
{
println!("is international");
}
else
{
println!("is not international");
}
}
#[cfg(test)]

View File

@@ -1,6 +1,11 @@
#[derive(Debug)]
enum Message {
// TODO: Define a few types of messages as used below.
Resize,
Move,
Echo,
ChangeColor,
Quit
}
fn main() {

View File

@@ -9,6 +9,11 @@ struct Point {
#[derive(Debug)]
enum Message {
// TODO: Define the different variants used below.
Resize { width: u16, height: u16 },
Move(Point),
Echo(String),
ChangeColor(u8, u8, u8),
Quit
}
impl Message {

View File

@@ -1,3 +1,5 @@
use std::str::Matches;
struct Point {
x: u64,
y: u64,
@@ -5,6 +7,11 @@ struct Point {
enum Message {
// TODO: Implement the message variant types based on their usage below.
Resize { width: u64, height: u64 },
Move(Point),
Echo(String),
ChangeColor(u8, u8, u8),
Quit
}
struct State {
@@ -42,6 +49,13 @@ impl State {
fn process(&mut self, message: Message) {
// TODO: Create a match expression to process the different message
// variants using the methods defined above.
match message {
Message::Resize { width, height } => self.resize(width, height),
Message::Move(point) => self.move_position(point),
Message::Echo(msg) => self.echo(msg),
Message::ChangeColor(r, g, b) => self.change_color(r, g, b),
Message::Quit => self.quit(),
}
}
}

View File

@@ -1,6 +1,6 @@
// TODO: Fix the compiler error without changing the function signature.
fn current_favorite_color() -> String {
"blue"
"blue".to_string()
}
fn main() {

View File

@@ -6,7 +6,7 @@ fn is_a_color_word(attempt: &str) -> bool {
fn main() {
let word = String::from("green"); // Don't change this line.
if is_a_color_word(word) {
if is_a_color_word(&word) {
println!("That is a color word I know!");
} else {
println!("That is not a color word I know.");

View File

@@ -1,13 +1,16 @@
fn trim_me(input: &str) -> &str {
// TODO: Remove whitespace from both ends of a string.
input.trim()
}
fn compose_me(input: &str) -> String {
// TODO: Add " world!" to the string! There are multiple ways to do this.
input.to_owned() + " world!"
}
fn replace_me(input: &str) -> String {
// TODO: Replace "cars" in the string with "balloons".
input.replace("cars", "balloons")
}
fn main() {

View File

@@ -13,25 +13,25 @@ fn string(arg: String) {
// Your task is to replace `placeholder(…)` with either `string_slice(…)`
// or `string(…)` depending on what you think each value is.
fn main() {
placeholder("blue");
string_slice("blue");
placeholder("red".to_string());
string("red".to_string());
placeholder(String::from("hi"));
string(String::from("hi"));
placeholder("rust is fun!".to_owned());
string("rust is fun!".to_owned());
placeholder("nice weather".into());
string("nice weather".into());
placeholder(format!("Interpolation {}", "Station"));
string(format!("Interpolation {}", "Station"));
// WARNING: This is byte indexing, not character indexing.
// Character indexing can be done using `s.chars().nth(INDEX)`.
placeholder(&String::from("abc")[0..1]);
string_slice(&String::from("abc")[0..1]);
placeholder(" hello there ".trim());
string_slice(" hello there ".trim());
placeholder("Happy Monday!".replace("Mon", "Tues"));
string("Happy Monday!".replace("Mon", "Tues"));
placeholder("mY sHiFt KeY iS sTiCkY".to_lowercase());
string("mY sHiFt KeY iS sTiCkY".to_lowercase());
}

View File

@@ -5,7 +5,7 @@ mod sausage_factory {
String::from("Ginger")
}
fn make_sausage() {
pub fn make_sausage() {
get_secret_recipe();
println!("sausage!");
}

View File

@@ -4,8 +4,8 @@
#[allow(dead_code)]
mod delicious_snacks {
// TODO: Add the following two `use` statements after fixing them.
// use self::fruits::PEAR as ???;
// use self::veggies::CUCUMBER as ???;
pub use self::fruits::PEAR as fruit;
pub use self::veggies::CUCUMBER as veggie;
mod fruits {
pub const PEAR: &str = "Pear";

View File

@@ -3,7 +3,7 @@
// TODO: Bring `SystemTime` and `UNIX_EPOCH` from the `std::time` module into
// your scope. Bonus style points if you can do it with one line!
// use ???;
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
match SystemTime::now().duration_since(UNIX_EPOCH) {

View File

@@ -8,12 +8,16 @@ use std::collections::HashMap;
fn fruit_basket() -> HashMap<String, u32> {
// TODO: Declare the hash map.
// let mut basket =
let mut basket = HashMap::new();
// Two bananas are already given for you :)
basket.insert(String::from("banana"), 2);
// TODO: Put more fruits in your basket.
basket.insert(String::from("apple"), 0);
basket.insert(String::from("ananas"), 3);
basket.insert(String::from("anananas"), 1);
basket.insert(String::from("pineapple"), 2);
basket
}

View File

@@ -32,6 +32,7 @@ fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
// TODO: Insert new fruits if they are not already present in the
// basket. Note that you are not allowed to put any type of fruit that's
// already present!
basket.entry(fruit).or_insert(1);
}
}

View File

@@ -17,7 +17,7 @@ struct TeamScores {
fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> {
// The name of the team is the key and its associated struct is the value.
let mut scores = HashMap::new();
let mut scores: HashMap<&str, TeamScores> = HashMap::new();
for line in results.lines() {
let mut split_iterator = line.split(',');
@@ -31,6 +31,32 @@ fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> {
// Keep in mind that goals scored by team 1 will be the number of goals
// conceded by team 2. Similarly, goals scored by team 2 will be the
// number of goals conceded by team 1.
let team = scores.get_mut(team_1_name);
match team {
Some(t) => {
t.goals_scored += team_1_score;
t.goals_conceded += team_2_score;
},
None => {
scores.insert(team_1_name, TeamScores {
goals_scored: team_1_score,
goals_conceded: team_2_score
});
}
}
let team = scores.get_mut(team_2_name);
match team {
Some(t) => {
t.goals_scored += team_2_score;
t.goals_conceded += team_1_score;
},
None => {
scores.insert(team_2_name, TeamScores {
goals_scored: team_2_score,
goals_conceded: team_1_score
});
}
}
}
scores

View File

@@ -4,6 +4,12 @@
// `hour_of_day` is higher than 23.
fn maybe_icecream(hour_of_day: u16) -> Option<u16> {
// TODO: Complete the function body.
match hour_of_day {
hour if hour<22 => Some(5),
hour if hour <24 => Some(0),
_ => None
}
}
fn main() {
@@ -18,7 +24,7 @@ mod tests {
fn raw_value() {
// TODO: Fix this test. How do you get the value contained in the
// Option?
let icecreams = maybe_icecream(12);
let icecreams = maybe_icecream(12).unwrap();
assert_eq!(icecreams, 5); // Don't change this line.
}

View File

@@ -10,7 +10,7 @@ mod tests {
let optional_target = Some(target);
// TODO: Make this an if-let statement whose value is `Some`.
word = optional_target {
if let Some(word) = optional_target {
assert_eq!(word, target);
}
}
@@ -29,9 +29,11 @@ mod tests {
// TODO: Make this a while-let statement. Remember that `Vec::pop()`
// adds another layer of `Option`. You can do nested pattern matching
// in if-let and while-let statements.
integer = optional_integers.pop() {
assert_eq!(integer, cursor);
cursor -= 1;
while let Some(integer_opt) = optional_integers.pop() {
if let Some(integer) = integer_opt {
assert_eq!(integer, cursor);
cursor -= 1;
}
}
assert_eq!(cursor, 0);

View File

@@ -9,7 +9,7 @@ fn main() {
// TODO: Fix the compiler error by adding something to this match statement.
match optional_point {
Some(p) => println!("Co-ordinates are {},{}", p.x, p.y),
Some(ref p) => println!("Co-ordinates are {},{}", p.x, p.y),
_ => panic!("No match!"),
}

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}"))
}
}

View File

@@ -22,8 +22,10 @@ fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
// TODO: Handle the error case as described above.
let qty = item_quantity.parse::<i32>();
Ok(qty * cost_per_item + processing_fee)
match qty {
Ok(x) => Ok(x * cost_per_item + processing_fee),
Err(x) => Err(x)
}
}
fn main() {

View File

@@ -2,7 +2,7 @@
// `total_cost` function from the previous exercise. It's not working though!
// Why not? What should we do to fix it?
use std::num::ParseIntError;
use std::{io::Empty, num::ParseIntError};
// Don't change this function.
fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
@@ -15,12 +15,12 @@ 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<(), ParseIntError>{
let mut tokens = 100;
let pretend_user_input = "8";
// Don't change this line.
let cost = total_cost(pretend_user_input)?;
let cost: i32 = total_cost(pretend_user_input)?;
if cost > tokens {
println!("You can't afford that many!");
@@ -28,4 +28,5 @@ fn main() {
tokens -= cost;
println!("You now have {tokens} tokens.");
}
Ok(())
}

View File

@@ -10,7 +10,11 @@ struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<Self, CreationError> {
// TODO: This function shouldn't always return an `Ok`.
Ok(Self(value as u64))
match value {
x if x < 0 => Err(CreationError::Negative),
0 => Err(CreationError::Zero),
_ => Ok(Self(value as u64))
}
}
}

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 std::error::Error>>{
let pretend_user_input = "42";
let x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?);

View File

@@ -25,7 +25,9 @@ impl ParsePosNonzeroError {
}
// TODO: Add another error conversion function here.
// fn from_parse_int(???) -> Self { ??? }
fn from_parse_int(err: ParseIntError) -> Self {
Self::ParseInt(err)
}
}
#[derive(PartialEq, Debug)]

View File

@@ -24,10 +24,22 @@ enum Command {
}
mod my_module {
use std::array;
use super::Command;
// TODO: Complete the function as described above.
// pub fn transformer(input: ???) -> ??? { ??? }
pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
let mut output = Vec::new();
for transform in input {
match transform.1 {
Command::Trim => output.push(transform.0.trim().to_string()),
Command::Uppercase => output.push(transform.0.to_uppercase()),
Command::Append(n) => output.push(transform.0 + &"bar".repeat(n))
}
}
output
}
}
fn main() {
@@ -37,7 +49,7 @@ fn main() {
#[cfg(test)]
mod tests {
// TODO: What do we need to import to have `transformer` in scope?
// use ???;
use crate::my_module::transformer;
use super::Command;
#[test]