mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-09 20:29:18 +00:00
parent
4639a94d6d
commit
453a65caef
@ -9,8 +9,6 @@
|
|||||||
// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
pub fn generate_nametag_text(name: String) -> Option<String> {
|
pub fn generate_nametag_text(name: String) -> Option<String> {
|
||||||
if name.is_empty() {
|
if name.is_empty() {
|
||||||
// Empty names aren't allowed.
|
// Empty names aren't allowed.
|
||||||
@ -28,14 +26,14 @@ mod tests {
|
|||||||
fn generates_nametag_text_for_a_nonempty_name() {
|
fn generates_nametag_text_for_a_nonempty_name() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
generate_nametag_text("Beyoncé".into()),
|
generate_nametag_text("Beyoncé".into()),
|
||||||
Ok("Hi! My name is Beyoncé".into())
|
Some("Hi! My name is Beyoncé".into())
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn explains_why_generating_nametag_text_fails() {
|
fn explains_why_generating_nametag_text_fails() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
generate_nametag_text("".into()),
|
generate_nametag_text("".into()).ok_or(String::from("`name` was empty; it must be nonempty.")),
|
||||||
// Don't change this line
|
// Don't change this line
|
||||||
Err("`name` was empty; it must be nonempty.".into())
|
Err("`name` was empty; it must be nonempty.".into())
|
||||||
);
|
);
|
||||||
|
|||||||
@ -19,14 +19,18 @@
|
|||||||
// Execute `rustlings hint errors2` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint errors2` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
use std::{num::ParseIntError, error::Error};
|
||||||
|
|
||||||
use std::num::ParseIntError;
|
|
||||||
|
|
||||||
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
|
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
|
||||||
let processing_fee = 1;
|
let processing_fee = 1;
|
||||||
let cost_per_item = 5;
|
let cost_per_item = 5;
|
||||||
let qty = item_quantity.parse::<i32>();
|
// long version...
|
||||||
|
// let qty = match (item_quantity.parse::<i32>()) {
|
||||||
|
// Ok(q) => q,
|
||||||
|
// Err(e) => return Err(e),
|
||||||
|
// };
|
||||||
|
// compact version -- using ?
|
||||||
|
let qty = item_quantity.parse::<i32>()?;
|
||||||
|
|
||||||
Ok(qty * cost_per_item + processing_fee)
|
Ok(qty * cost_per_item + processing_fee)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,15 +7,16 @@
|
|||||||
// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::num::ParseIntError;
|
use std::num::ParseIntError;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let mut tokens = 100;
|
let mut tokens = 100;
|
||||||
let pretend_user_input = "8";
|
let pretend_user_input = "8";
|
||||||
|
|
||||||
let cost = total_cost(pretend_user_input)?;
|
let cost = match total_cost(pretend_user_input) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => panic!("Error"),
|
||||||
|
};
|
||||||
|
|
||||||
if cost > tokens {
|
if cost > tokens {
|
||||||
println!("You can't afford that many!");
|
println!("You can't afford that many!");
|
||||||
|
|||||||
@ -3,8 +3,6 @@
|
|||||||
// Execute `rustlings hint errors4` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint errors4` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
#[derive(PartialEq, Debug)]
|
#[derive(PartialEq, Debug)]
|
||||||
struct PositiveNonzeroInteger(u64);
|
struct PositiveNonzeroInteger(u64);
|
||||||
|
|
||||||
@ -16,8 +14,16 @@ enum CreationError {
|
|||||||
|
|
||||||
impl PositiveNonzeroInteger {
|
impl PositiveNonzeroInteger {
|
||||||
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
|
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
|
||||||
// Hmm... Why is this always returning an Ok value?
|
// Hmm...? Why is this only returning an Ok value?
|
||||||
Ok(PositiveNonzeroInteger(value as u64))
|
if(value > 0) {
|
||||||
|
Ok(PositiveNonzeroInteger(value as u64))
|
||||||
|
} else {
|
||||||
|
if(value == 0) {
|
||||||
|
Err(CreationError::Zero)
|
||||||
|
} else {
|
||||||
|
Err(CreationError::Negative)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -22,14 +22,13 @@
|
|||||||
// Execute `rustlings hint errors5` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint errors5` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::error;
|
use std::error;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
use std::fmt::Debug;
|
||||||
use std::num::ParseIntError;
|
use std::num::ParseIntError;
|
||||||
|
|
||||||
// TODO: update the return type of `main()` to make this compile.
|
// TODO: update the return type of `main()` to make this compile.
|
||||||
fn main() -> Result<(), Box<dyn ???>> {
|
fn main() -> Result<(), Box<dyn error::Error>> {
|
||||||
let pretend_user_input = "42";
|
let pretend_user_input = "42";
|
||||||
let x: i64 = pretend_user_input.parse()?;
|
let x: i64 = pretend_user_input.parse()?;
|
||||||
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
|
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
|
||||||
|
|||||||
@ -9,8 +9,6 @@
|
|||||||
// Execute `rustlings hint errors6` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint errors6` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::num::ParseIntError;
|
use std::num::ParseIntError;
|
||||||
|
|
||||||
// This is a custom error type that we will be using in `parse_pos_nonzero()`.
|
// This is a custom error type that we will be using in `parse_pos_nonzero()`.
|
||||||
@ -25,14 +23,23 @@ impl ParsePosNonzeroError {
|
|||||||
ParsePosNonzeroError::Creation(err)
|
ParsePosNonzeroError::Creation(err)
|
||||||
}
|
}
|
||||||
// TODO: add another error conversion function here.
|
// TODO: add another error conversion function here.
|
||||||
// fn from_parseint...
|
fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError {
|
||||||
|
ParsePosNonzeroError::ParseInt(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_pos_nonzero(s: &str) -> Result<PositiveNonzeroInteger, ParsePosNonzeroError> {
|
fn parse_pos_nonzero(s: &str) -> Result<PositiveNonzeroInteger, ParsePosNonzeroError> {
|
||||||
// TODO: change this to return an appropriate error instead of panicking
|
// TODO: change this to return an appropriate error instead of panicking
|
||||||
// when `parse()` returns an error.
|
// when `parse()` returns an error.
|
||||||
let x: i64 = s.parse().unwrap();
|
match s.parse() {
|
||||||
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
|
Ok(n) =>
|
||||||
|
match PositiveNonzeroInteger::new(n) {
|
||||||
|
Ok(x) => Ok(x),
|
||||||
|
Err(e1) => Err(ParsePosNonzeroError::from_creation(e1)),
|
||||||
|
},
|
||||||
|
Err(e) => Err(e).map_err(ParsePosNonzeroError::from_parseint),
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Don't change anything below this line.
|
// Don't change anything below this line.
|
||||||
|
|||||||
@ -6,9 +6,7 @@
|
|||||||
// Execute `rustlings hint generics1` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint generics1` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let mut shopping_list: Vec<?> = Vec::new();
|
let mut shopping_list: Vec<&str> = Vec::new();
|
||||||
shopping_list.push("milk");
|
shopping_list.push("milk");
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,14 +6,12 @@
|
|||||||
// Execute `rustlings hint generics2` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint generics2` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
struct Wrapper<T> {
|
||||||
|
value: T,
|
||||||
struct Wrapper {
|
|
||||||
value: u32,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Wrapper {
|
impl<T> Wrapper<T> {
|
||||||
pub fn new(value: u32) -> Self {
|
pub fn new(value: T) -> Self {
|
||||||
Wrapper { value }
|
Wrapper { value }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -11,8 +11,6 @@
|
|||||||
// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// 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> {
|
||||||
|
|||||||
@ -14,8 +14,6 @@
|
|||||||
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
#[derive(Hash, PartialEq, Eq)]
|
#[derive(Hash, PartialEq, Eq)]
|
||||||
@ -40,6 +38,7 @@ fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
|
|||||||
// TODO: Insert new fruits if they are not already present in the
|
// 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
|
// basket. Note that you are not allowed to put any type of fruit that's
|
||||||
// already present!
|
// already present!
|
||||||
|
basket.entry(fruit).or_insert(3);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -14,8 +14,6 @@
|
|||||||
// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
// A structure to store the goal details of a team.
|
// A structure to store the goal details of a team.
|
||||||
@ -39,7 +37,15 @@ fn build_scores_table(results: String) -> HashMap<String, Team> {
|
|||||||
// 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.
|
||||||
|
|
||||||
|
// Try to insert a team name with a default Team score struct (all 0s)
|
||||||
|
let t1 = scores.entry(team_1_name).or_insert(Team { goals_scored: 0, goals_conceded: 0});
|
||||||
|
// update the Team struct with the right amount of goals (if new insert with the values just parsed, otherwise added to the prev values)
|
||||||
|
*t1 = Team { goals_scored: t1.goals_scored + team_1_score, goals_conceded: t1.goals_conceded + team_2_score };
|
||||||
|
let t2 = scores.entry(team_2_name).or_insert(Team { goals_scored: 0, goals_conceded: 0});
|
||||||
|
*t2 = Team { goals_scored: t2.goals_scored + team_2_score, goals_conceded: t2.goals_conceded + team_1_score };
|
||||||
}
|
}
|
||||||
|
|
||||||
scores
|
scores
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -3,8 +3,6 @@
|
|||||||
// Execute `rustlings hint options1` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint options1` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// 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 :(
|
||||||
@ -13,7 +11,15 @@ fn maybe_icecream(time_of_day: u16) -> Option<u16> {
|
|||||||
// value of 0 The Option output should gracefully handle cases where
|
// value of 0 The Option output should gracefully handle cases where
|
||||||
// time_of_day > 23.
|
// time_of_day > 23.
|
||||||
// TODO: Complete the function body - remember to return an Option!
|
// TODO: Complete the function body - remember to return an Option!
|
||||||
???
|
if time_of_day > 23 {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
if time_of_day >= 22 {
|
||||||
|
Some(0)
|
||||||
|
} else {
|
||||||
|
Some(5)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@ -33,7 +39,8 @@ mod tests {
|
|||||||
fn raw_value() {
|
fn raw_value() {
|
||||||
// TODO: Fix this test. How do you get at the value contained in the
|
// TODO: Fix this test. How do you get at the value contained in the
|
||||||
// Option?
|
// Option?
|
||||||
let icecreams = maybe_icecream(12);
|
if let Some(icecreams ) = maybe_icecream(12) {
|
||||||
assert_eq!(icecreams, 5);
|
assert_eq!(icecreams, 5);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,8 +3,6 @@
|
|||||||
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
@ -13,7 +11,7 @@ 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -32,9 +30,11 @@ mod tests {
|
|||||||
// TODO: make this a while let statement - remember that vector.pop also
|
// 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
|
// adds another layer of Option<T>. You can stack `Option<T>`s into
|
||||||
// while let and if let.
|
// while let and if let.
|
||||||
integer = optional_integers.pop() {
|
while let Some(optional) = optional_integers.pop() {
|
||||||
assert_eq!(integer, cursor);
|
if let Some(integer) = optional {
|
||||||
cursor -= 1;
|
assert_eq!(integer, cursor);
|
||||||
|
cursor -= 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
assert_eq!(cursor, 0);
|
assert_eq!(cursor, 0);
|
||||||
|
|||||||
@ -3,15 +3,18 @@
|
|||||||
// Execute `rustlings hint options3` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint options3` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
// I can use the Copy (and clone) typeclasses
|
||||||
|
//#[derive(Clone, Copy)]
|
||||||
struct Point {
|
struct Point {
|
||||||
x: i32,
|
x: i32,
|
||||||
y: i32,
|
y: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let y: Option<Point> = Some(Point { x: 100, y: 200 });
|
// if I use the typeclasses this stay clean
|
||||||
|
//let y: Option<Point> = Some(Point { x: 100, y: 200 });
|
||||||
|
// or I can use the reference in the pattern, adding the &
|
||||||
|
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(p) => println!("Co-ordinates are {},{} ", p.x, p.y),
|
||||||
|
|||||||
@ -20,8 +20,6 @@
|
|||||||
//
|
//
|
||||||
// No hints this time!
|
// No hints this time!
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
pub enum Command {
|
pub enum Command {
|
||||||
Uppercase,
|
Uppercase,
|
||||||
Trim,
|
Trim,
|
||||||
@ -32,11 +30,16 @@ 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()),
|
||||||
|
Command::Trim => output.push(string.trim().to_string()),
|
||||||
|
Command::Append(n) => output.push(format!("{}{}", string, "bar".repeat(*n))),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
output
|
output
|
||||||
}
|
}
|
||||||
@ -45,7 +48,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 crate::my_module::transformer;
|
||||||
use super::Command;
|
use super::Command;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@ -7,14 +7,15 @@
|
|||||||
// Execute `rustlings hint traits1` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint traits1` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
trait AppendBar {
|
trait AppendBar {
|
||||||
fn append_bar(self) -> Self;
|
fn append_bar(&self) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppendBar for String {
|
impl AppendBar for String {
|
||||||
// TODO: Implement `AppendBar` for type `String`.
|
// TODO: Implement `AppendBar` for type `String`.
|
||||||
|
fn append_bar(&self) -> Self {
|
||||||
|
format!("{}{}", self, "Bar")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user