Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
Adooobe committed Jan 25, 2025
1 parent 80067e9 commit 061a54e
Show file tree
Hide file tree
Showing 13 changed files with 75 additions and 34 deletions.
7 changes: 3 additions & 4 deletions exercises/error_handling/errors1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,13 @@
// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

pub fn generate_nametag_text(name: String) -> Option<String> {
pub fn generate_nametag_text(name: String) -> Result<String, String> {
if name.is_empty() {
// Empty names aren't allowed.
None
Err("`name` was empty; it must be nonempty.".into())
} else {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
}
}

Expand Down
3 changes: 1 addition & 2 deletions exercises/error_handling/errors2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,13 @@
// Execute `rustlings hint errors2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::num::ParseIntError;

pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>();
let qty = item_quantity.parse::<i32>()?;

Ok(qty * cost_per_item + processing_fee)
}
Expand Down
6 changes: 3 additions & 3 deletions exercises/error_handling/errors3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,21 @@
// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::num::ParseIntError;

fn main() {
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut tokens = 100;
let pretend_user_input = "8";

let cost = total_cost(pretend_user_input)?;

if cost > tokens {
println!("You can't afford that many!");
Ok(())
} else {
tokens -= cost;
println!("You now have {} tokens.", tokens);
Ok(())
}
}

Expand Down
5 changes: 3 additions & 2 deletions exercises/hashmaps/hashmaps1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@
// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::collections::HashMap;

fn fruit_basket() -> HashMap<String, u32> {
let mut basket = // TODO: declare your hash map here.
let mut basket = HashMap::new();

// Two bananas are already given for you :)
basket.insert(String::from("banana"), 2);
basket.insert(String::from("apple"), 3);
basket.insert(String::from("tomato"), 3);

// TODO: Put more fruits in your basket here.

Expand Down
4 changes: 3 additions & 1 deletion exercises/hashmaps/hashmaps2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::collections::HashMap;

Expand All @@ -40,6 +39,9 @@ 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!
if !basket.contains_key(&fruit) {
basket.insert(fruit, 1);
}
}
}

Expand Down
25 changes: 24 additions & 1 deletion exercises/hashmaps/hashmaps3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::collections::HashMap;

Expand All @@ -34,6 +33,30 @@ fn build_scores_table(results: String) -> HashMap<String, Team> {
let team_1_score: u8 = v[2].parse().unwrap();
let team_2_name = v[1].to_string();
let team_2_score: u8 = v[3].parse().unwrap();


let update_team = |team: &mut Team, scored: u8, conceded: u8| {
team.goals_scored += scored;
team.goals_conceded += conceded;
};

scores.entry(team_1_name)
.and_modify(|t| update_team(t, team_1_score, team_2_score))
.or_insert(Team {
goals_scored: team_1_score,
goals_conceded: team_2_score,
});

scores.entry(team_2_name)
.and_modify(|t| update_team(t, team_2_score, team_1_score))
.or_insert(Team {
goals_scored: team_2_score,
goals_conceded: team_1_score,
});
// scores.insert(team_2_name, Team{
// goals_conceded: team_1_score,
// goals_scored: team_2_score,
// });
// TODO: Populate the scores table with details extracted from the
// current line. Keep in mind that goals scored by team_1
// will be the number of goals conceded from team_2, and similarly
Expand Down
3 changes: 1 addition & 2 deletions exercises/modules/modules1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@
// Execute `rustlings hint modules1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

mod sausage_factory {
// Don't let anybody outside of this module see this!
fn get_secret_recipe() -> String {
String::from("Ginger")
}

fn make_sausage() {
pub fn make_sausage() {
get_secret_recipe();
println!("sausage!");
}
Expand Down
5 changes: 2 additions & 3 deletions exercises/modules/modules2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@
// Execute `rustlings hint modules2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

mod delicious_snacks {
// TODO: Fix these use statements
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: &'static str = "Pear";
Expand Down
4 changes: 2 additions & 2 deletions exercises/modules/modules3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
// Execute `rustlings hint modules3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

// TODO: Complete this use statement
use ???
use std::time::UNIX_EPOCH as UNIX_EPOCH;
use std::time::SystemTime;

fn main() {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Expand Down
11 changes: 8 additions & 3 deletions exercises/options/options1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
// Execute `rustlings hint options1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use core::time;

// This function returns how much icecream there is left in the fridge.
// If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them
Expand All @@ -13,7 +14,11 @@ fn maybe_icecream(time_of_day: u16) -> Option<u16> {
// value of 0 The Option output should gracefully handle cases where
// time_of_day > 23.
// TODO: Complete the function body - remember to return an Option!
???
match time_of_day {
t if (t>=0 &&t < 22) => {Some(5)}, // 22点之前返回5个冰淇淋
t if (t>=22 && t< 24) => Some(0), // 22点或23点返回0个冰淇淋
_ => None, // 其他情况(如时间大于23)返回None
}
}

#[cfg(test)]
Expand All @@ -33,7 +38,7 @@ mod tests {
fn raw_value() {
// TODO: Fix this test. How do you get at the value contained in the
// Option?
let icecreams = maybe_icecream(12);
let icecreams = maybe_icecream(12).unwrap();
assert_eq!(icecreams, 5);
}
}
7 changes: 3 additions & 4 deletions exercises/options/options2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

#[cfg(test)]
mod tests {
Expand All @@ -13,8 +12,8 @@ mod tests {
let optional_target = Some(target);

// TODO: Make this an if let statement whose value is "Some" type
word = optional_target {
assert_eq!(word, target);
if let Some(word) = optional_target {
assert_eq!(word, target)
}
}

Expand All @@ -32,7 +31,7 @@ mod tests {
// TODO: make this a while let statement - remember that vector.pop also
// adds another layer of Option<T>. You can stack `Option<T>`s into
// while let and if let.
integer = optional_integers.pop() {
while let Some(Some(integer)) = optional_integers.pop() {
assert_eq!(integer, cursor);
cursor -= 1;
}
Expand Down
3 changes: 1 addition & 2 deletions exercises/options/options3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// Execute `rustlings hint options3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

struct Point {
x: i32,
Expand All @@ -13,7 +12,7 @@ struct Point {
fn main() {
let y: Option<Point> = Some(Point { x: 100, y: 200 });

match y {
match &y {
Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y),
_ => panic!("no match!"),
}
Expand Down
26 changes: 21 additions & 5 deletions exercises/quiz2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
//
// No hints this time!

// I AM NOT DONE

pub enum Command {
Uppercase,
Expand All @@ -29,14 +28,31 @@ pub enum Command {
}

mod my_module {

use super::Command;

// TODO: Complete the function signature!
pub fn transformer(input: ???) -> ??? {
pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
// TODO: Complete the output declaration!
let mut output: ??? = vec![];
let mut output: Vec<String> = vec![];
for (string, command) in input.iter() {
// TODO: Complete the function body. You can do it!
match command {
Command::Trim => {
output.push(String::from(string.trim()));
},
Command::Append(_x) => {
let mut s = string.clone();
for _ in 0..*_x {
s.push_str(string);
}
output.push(s);
},

Command::Uppercase => {
output.push(string.to_uppercase());
}
}
}
output
}
Expand All @@ -45,7 +61,7 @@ mod my_module {
#[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]
Expand All @@ -58,7 +74,7 @@ mod tests {
]);
assert_eq!(output[0], "HELLO");
assert_eq!(output[1], "all roads lead to rome!");
assert_eq!(output[2], "foobar");
assert_eq!(output[2], "foofoo");
assert_eq!(output[3], "barbarbarbarbarbar");
}
}

0 comments on commit 061a54e

Please sign in to comment.