mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-11 13:19:18 +00:00
through errors1
This commit is contained in:
parent
201d9f8176
commit
d3caa3301e
@ -2,10 +2,7 @@
|
|||||||
// Address all the TODOs to make the tests pass!
|
// Address all the TODOs to make the tests pass!
|
||||||
// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
enum Message {
|
enum Message {
|
||||||
// TODO: implement the message variant types based on their usage below
|
|
||||||
Move(Point),
|
Move(Point),
|
||||||
Echo(String),
|
Echo(String),
|
||||||
ChangeColor((u8, u8, u8)),
|
ChangeColor((u8, u8, u8)),
|
||||||
|
|||||||
@ -5,14 +5,10 @@
|
|||||||
// construct to `Option` that can be used to express error conditions. Let's use it!
|
// construct to `Option` that can be used to express error conditions. Let's use it!
|
||||||
// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
pub fn generate_nametag_text(name: String) -> Result<String, String> {
|
||||||
|
match name {
|
||||||
pub fn generate_nametag_text(name: String) -> Option<String> {
|
name if name.is_empty() => Err("`name` was empty; it must be nonempty.".into()),
|
||||||
if name.is_empty() {
|
name => Ok(format!("Hi! My name is {}", name)),
|
||||||
// Empty names aren't allowed.
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(format!("Hi! My name is {}", name))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -10,18 +10,17 @@
|
|||||||
//
|
//
|
||||||
// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
fn fruit_basket() -> HashMap<String, u32> {
|
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 :)
|
// Two bananas are already given for you :)
|
||||||
basket.insert(String::from("banana"), 2);
|
basket.insert(String::from("banana"), 2);
|
||||||
|
|
||||||
// TODO: Put more fruits in your basket here.
|
// TODO: Put more fruits in your basket here.
|
||||||
|
basket.insert(String::from("apple"), 4);
|
||||||
|
basket.insert(String::from("kiwi"), 4);
|
||||||
basket
|
basket
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -11,8 +11,6 @@
|
|||||||
//
|
//
|
||||||
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
#[derive(Hash, PartialEq, Eq)]
|
#[derive(Hash, PartialEq, Eq)]
|
||||||
@ -34,9 +32,9 @@ fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
|
|||||||
];
|
];
|
||||||
|
|
||||||
for fruit in fruit_kinds {
|
for fruit in fruit_kinds {
|
||||||
// TODO: Put new fruits if not already present. Note that you
|
if !basket.contains_key(&fruit) {
|
||||||
// are not allowed to put any type of fruit that's already
|
basket.insert(fruit, 1);
|
||||||
// present!
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -14,8 +14,6 @@
|
|||||||
|
|
||||||
// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
// A structure to store team name and its goal details.
|
// A structure to store team name and its goal details.
|
||||||
@ -25,22 +23,41 @@ struct Team {
|
|||||||
goals_conceded: u8,
|
goals_conceded: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add or update an entry in the scores table
|
||||||
|
fn update_hash(scores: &mut HashMap<String, Team>, name: &str, score: u8, scored_upon: u8) {
|
||||||
|
scores
|
||||||
|
.entry(name.to_string())
|
||||||
|
.and_modify(|team| {
|
||||||
|
team.goals_scored += score;
|
||||||
|
team.goals_conceded += scored_upon;
|
||||||
|
})
|
||||||
|
.or_insert(Team {
|
||||||
|
name: name.to_string(),
|
||||||
|
goals_scored: score,
|
||||||
|
goals_conceded: scored_upon,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
fn build_scores_table(results: String) -> HashMap<String, Team> {
|
fn build_scores_table(results: String) -> HashMap<String, Team> {
|
||||||
// The name of the team is the key and its associated struct is the value.
|
// The name of the team is the key and its associated struct is the value.
|
||||||
let mut scores: HashMap<String, Team> = HashMap::new();
|
let mut scores: HashMap<String, Team> = HashMap::new();
|
||||||
|
|
||||||
for r in results.lines() {
|
for r in results.lines() {
|
||||||
let v: Vec<&str> = r.split(',').collect();
|
let v: Vec<&str> = r.split(',').collect();
|
||||||
let team_1_name = v[0].to_string();
|
|
||||||
let team_1_score: u8 = v[2].parse().unwrap();
|
let (team_1_name, team_1_score): (&str, u8) = (v[0], v[2].parse().unwrap());
|
||||||
let team_2_name = v[1].to_string();
|
let (team_2_name, team_2_score): (&str, u8) = (v[1], v[3].parse().unwrap());
|
||||||
let team_2_score: u8 = v[3].parse().unwrap();
|
|
||||||
// TODO: Populate the scores table with details extracted from the
|
// TODO: Populate the scores table with details extracted from the
|
||||||
// current line. Keep in mind that goals scored by team_1
|
// current line. Keep in mind that goals scored by team_1
|
||||||
// will be the number of goals conceded from team_2, and similarly
|
// will be the number of goals conceded from team_2, and similarly
|
||||||
// goals scored by team_2 will be the number of goals conceded by
|
// goals scored by team_2 will be the number of goals conceded by
|
||||||
// team_1.
|
// team_1
|
||||||
|
|
||||||
|
update_hash(&mut scores, team_1_name, team_1_score, team_2_score);
|
||||||
|
update_hash(&mut scores, team_2_name, team_2_score, team_1_score);
|
||||||
}
|
}
|
||||||
|
|
||||||
scores
|
scores
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,15 +1,13 @@
|
|||||||
// modules1.rs
|
// modules1.rs
|
||||||
// Execute `rustlings hint modules1` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint modules1` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
mod sausage_factory {
|
mod sausage_factory {
|
||||||
// Don't let anybody outside of this module see this!
|
// Don't let anybody outside of this module see this!
|
||||||
fn get_secret_recipe() -> String {
|
fn get_secret_recipe() -> String {
|
||||||
String::from("Ginger")
|
String::from("Ginger")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn make_sausage() {
|
pub fn make_sausage() {
|
||||||
get_secret_recipe();
|
get_secret_recipe();
|
||||||
println!("sausage!");
|
println!("sausage!");
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,12 +3,10 @@
|
|||||||
// 'use' and 'as' keywords. Fix these 'use' statements to make the code compile.
|
// 'use' and 'as' keywords. Fix these 'use' statements to make the code compile.
|
||||||
// Execute `rustlings hint modules2` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint modules2` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
mod delicious_snacks {
|
mod delicious_snacks {
|
||||||
// TODO: Fix these use statements
|
// TODO: Fix these use statements
|
||||||
use self::fruits::PEAR as ???
|
pub use self::fruits::PEAR as fruit;
|
||||||
use self::veggies::CUCUMBER as ???
|
pub use self::veggies::CUCUMBER as veggie;
|
||||||
|
|
||||||
mod fruits {
|
mod fruits {
|
||||||
pub const PEAR: &'static str = "Pear";
|
pub const PEAR: &'static str = "Pear";
|
||||||
|
|||||||
@ -5,10 +5,8 @@
|
|||||||
// from the std::time module. Bonus style points if you can do it with one line!
|
// from the std::time module. Bonus style points if you can do it with one line!
|
||||||
// Execute `rustlings hint modules3` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint modules3` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
// TODO: Complete this use statement
|
// TODO: Complete this use statement
|
||||||
use ???
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
match SystemTime::now().duration_since(UNIX_EPOCH) {
|
match SystemTime::now().duration_since(UNIX_EPOCH) {
|
||||||
|
|||||||
@ -1,8 +1,6 @@
|
|||||||
// options1.rs
|
// options1.rs
|
||||||
// Execute `rustlings hint options1` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint options1` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
// This function returns how much icecream there is left in the fridge.
|
// 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
|
// If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them
|
||||||
// all, so there'll be no more left :(
|
// all, so there'll be no more left :(
|
||||||
@ -10,7 +8,11 @@ fn maybe_icecream(time_of_day: u16) -> Option<u16> {
|
|||||||
// We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a value of 0
|
// We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a value of 0
|
||||||
// The Option output should gracefully handle cases where time_of_day > 23.
|
// The Option output should gracefully handle cases where time_of_day > 23.
|
||||||
// TODO: Complete the function body - remember to return an Option!
|
// TODO: Complete the function body - remember to return an Option!
|
||||||
???
|
match time_of_day {
|
||||||
|
0..=21 => Some(5),
|
||||||
|
22..=24 => Some(0),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@ -29,7 +31,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn raw_value() {
|
fn raw_value() {
|
||||||
// TODO: Fix this test. How do you get at the value contained in the Option?
|
// 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);
|
assert_eq!(icecreams, 5);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,6 @@
|
|||||||
// options2.rs
|
// options2.rs
|
||||||
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@ -13,9 +11,9 @@ mod tests {
|
|||||||
let optional_target = Some(target);
|
let optional_target = Some(target);
|
||||||
|
|
||||||
// TODO: Make this an if let statement whose value is "Some" type
|
// TODO: Make this an if let statement whose value is "Some" type
|
||||||
word = optional_target {
|
if let Some(word) = optional_target {
|
||||||
assert_eq!(word, target);
|
assert_eq!(word, target);
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -28,7 +26,7 @@ mod tests {
|
|||||||
|
|
||||||
// TODO: make this a while let statement - remember that vector.pop also adds another layer of Option<T>
|
// 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
|
// You can stack `Option<T>`'s into while let and if let
|
||||||
integer = optional_integers.pop() {
|
while let Some(integer) = optional_integers.pop().flatten() {
|
||||||
assert_eq!(integer, range);
|
assert_eq!(integer, range);
|
||||||
range -= 1;
|
range -= 1;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,6 @@
|
|||||||
// options3.rs
|
// options3.rs
|
||||||
// Execute `rustlings hint options3` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint options3` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
struct Point {
|
struct Point {
|
||||||
x: i32,
|
x: i32,
|
||||||
y: i32,
|
y: i32,
|
||||||
@ -12,7 +10,7 @@ fn main() {
|
|||||||
let y: Option<Point> = Some(Point { x: 100, y: 200 });
|
let y: Option<Point> = Some(Point { x: 100, y: 200 });
|
||||||
|
|
||||||
match y {
|
match y {
|
||||||
Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y),
|
Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y),
|
||||||
_ => println!("no match"),
|
_ => println!("no match"),
|
||||||
}
|
}
|
||||||
y; // Fix without deleting this line.
|
y; // Fix without deleting this line.
|
||||||
|
|||||||
@ -18,8 +18,6 @@
|
|||||||
// - The output element is going to be a Vector of strings.
|
// - The output element is going to be a Vector of strings.
|
||||||
// No hints this time!
|
// No hints this time!
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
pub enum Command {
|
pub enum Command {
|
||||||
Uppercase,
|
Uppercase,
|
||||||
Trim,
|
Trim,
|
||||||
@ -30,11 +28,17 @@ mod my_module {
|
|||||||
use super::Command;
|
use super::Command;
|
||||||
|
|
||||||
// TODO: Complete the function signature!
|
// TODO: Complete the function signature!
|
||||||
pub fn transformer(input: ???) -> ??? {
|
pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
|
||||||
// TODO: Complete the output declaration!
|
// TODO: Complete the output declaration!
|
||||||
let mut output: ??? = vec![];
|
let mut output: Vec<String> = vec![];
|
||||||
|
|
||||||
for (string, command) in input.iter() {
|
for (string, command) in input.iter() {
|
||||||
// TODO: Complete the function body. You can do it!
|
// TODO: Complete the function body. You can do it!
|
||||||
|
match command {
|
||||||
|
Command::Uppercase => output.push(string.to_uppercase().to_string()),
|
||||||
|
Command::Trim => output.push(string.trim().to_string()),
|
||||||
|
Command::Append(size) => output.push(string.to_owned() + &"bar".repeat(*size)),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
output
|
output
|
||||||
}
|
}
|
||||||
@ -43,7 +47,7 @@ mod my_module {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
// TODO: What do we need to import to have `transformer` in scope?
|
// TODO: What do we need to import to have `transformer` in scope?
|
||||||
use ???;
|
use super::my_module::transformer;
|
||||||
use super::Command;
|
use super::Command;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@ -2,13 +2,11 @@
|
|||||||
// Make me compile without changing the function signature!
|
// Make me compile without changing the function signature!
|
||||||
// Execute `rustlings hint strings1` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint strings1` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let answer = current_favorite_color();
|
let answer = current_favorite_color();
|
||||||
println!("My current favorite color is {}", answer);
|
println!("My current favorite color is {}", answer);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn current_favorite_color() -> String {
|
fn current_favorite_color() -> String {
|
||||||
"blue"
|
String::from("blue")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,8 +2,6 @@
|
|||||||
// Make me compile without changing the function signature!
|
// Make me compile without changing the function signature!
|
||||||
// Execute `rustlings hint strings2` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint strings2` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let word = String::from("green"); // Try not changing this line :)
|
let word = String::from("green"); // Try not changing this line :)
|
||||||
if is_a_color_word(word) {
|
if is_a_color_word(word) {
|
||||||
@ -13,6 +11,6 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_a_color_word(attempt: &str) -> bool {
|
fn is_a_color_word(attempt: String) -> bool {
|
||||||
attempt == "green" || attempt == "blue" || attempt == "red"
|
attempt == "green" || attempt == "blue" || attempt == "red"
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,21 +1,17 @@
|
|||||||
// strings3.rs
|
// strings3.rs
|
||||||
// Execute `rustlings hint strings3` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint strings3` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
fn trim_me(input: &str) -> String {
|
fn trim_me(input: &str) -> String {
|
||||||
// TODO: Remove whitespace from both ends of a string!
|
input.trim().to_string()
|
||||||
???
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn compose_me(input: &str) -> String {
|
fn compose_me(input: &str) -> String {
|
||||||
// TODO: Add " world!" to the string! There's multiple ways to do this!
|
format!("{input} world!").to_string()
|
||||||
???
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn replace_me(input: &str) -> String {
|
fn replace_me(input: &str) -> String {
|
||||||
// TODO: Replace "cars" in the string with "balloons"!
|
// TODO: Replace "cars" in the string with "balloons"!
|
||||||
???
|
input.to_string().replace("cars", "balloons")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@ -37,7 +33,13 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn replace_a_string() {
|
fn replace_a_string() {
|
||||||
assert_eq!(replace_me("I think cars are cool"), "I think balloons are cool");
|
assert_eq!(
|
||||||
assert_eq!(replace_me("I love to look at cars"), "I love to look at balloons");
|
replace_me("I think cars are cool"),
|
||||||
|
"I think balloons are cool"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
replace_me("I love to look at cars"),
|
||||||
|
"I love to look at balloons"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,8 +6,6 @@
|
|||||||
// before the parentheses on each line. If you're right, it will compile!
|
// before the parentheses on each line. If you're right, it will compile!
|
||||||
// No hints this time!
|
// No hints this time!
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
fn string_slice(arg: &str) {
|
fn string_slice(arg: &str) {
|
||||||
println!("{}", arg);
|
println!("{}", arg);
|
||||||
}
|
}
|
||||||
@ -16,14 +14,14 @@ fn string(arg: String) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
???("blue");
|
string_slice("blue");
|
||||||
???("red".to_string());
|
string("red".to_string());
|
||||||
???(String::from("hi"));
|
string(String::from("hi"));
|
||||||
???("rust is fun!".to_owned());
|
string("rust is fun!".to_owned());
|
||||||
???("nice weather".into());
|
string("nice weather".into());
|
||||||
???(format!("Interpolation {}", "Station"));
|
string(format!("Interpolation {}", "Station"));
|
||||||
???(&String::from("abc")[0..1]);
|
string_slice(&String::from("abc")[0..1]);
|
||||||
???(" hello there ".trim());
|
string_slice(" hello there ".trim());
|
||||||
???("Happy Monday!".to_string().replace("Mon", "Tues"));
|
string("Happy Monday!".to_string().replace("Mon", "Tues"));
|
||||||
???("mY sHiFt KeY iS sTiCkY".to_lowercase());
|
string("mY sHiFt KeY iS sTiCkY".to_lowercase());
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user