Skip to content

Commit e4c5d83

Browse files
committed
1
1 parent ade0692 commit e4c5d83

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+225
-273
lines changed

exercises/enums/enums1.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22
//
33
// No hints this time! ;)
44

5-
// I AM NOT DONE
65

76
#[derive(Debug)]
87
enum Message {
98
// TODO: define a few types of messages as used below
9+
Quit,
10+
Echo,
11+
Move,
12+
ChangeColor
1013
}
1114

1215
fn main() {

exercises/enums/enums2.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,14 @@
33
// Execute `rustlings hint enums2` or use the `hint` watch subcommand for a
44
// hint.
55

6-
// I AM NOT DONE
76

87
#[derive(Debug)]
98
enum Message {
109
// TODO: define the different variants used below
10+
Move{x:i32, y:i32},
11+
Echo(String),
12+
ChangeColor(u8,u8,u8),
13+
Quit
1114
}
1215

1316
impl Message {

exercises/enums/enums3.rs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@
55
// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a
66
// hint.
77

8-
// I AM NOT DONE
9-
108
enum Message {
11-
// TODO: implement the message variant types based on their usage below
9+
// TODO: define the different variants used below
10+
Move(Point),
11+
Echo(String),
12+
ChangeColor(u8,u8,u8),
13+
Quit
1214
}
1315

1416
struct Point {
@@ -43,6 +45,12 @@ impl State {
4345
// variants
4446
// Remember: When passing a tuple as a function argument, you'll need
4547
// extra parentheses: fn function((t, u, p, l, e))
48+
match message {
49+
Message::Move(x) => self.move_position(x),
50+
Message::ChangeColor(x, y, z) => self.change_color((x, y, z)),
51+
Message::Quit => self.quit(),
52+
Message::Echo(x) => self.echo(x),
53+
};
4654
}
4755
}
4856

exercises/error_handling/errors1.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,12 @@
99
// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a
1010
// hint.
1111

12-
// I AM NOT DONE
13-
14-
pub fn generate_nametag_text(name: String) -> Option<String> {
12+
pub fn generate_nametag_text(name: String) -> Result<String, String> {
1513
if name.is_empty() {
1614
// Empty names aren't allowed.
17-
None
15+
Err("`name` was empty; it must be nonempty.".into())
1816
} else {
19-
Some(format!("Hi! My name is {}", name))
17+
Ok(format!("Hi! My name is {}", name))
2018
}
2119
}
2220

@@ -40,4 +38,4 @@ mod tests {
4038
Err("`name` was empty; it must be nonempty.".into())
4139
);
4240
}
43-
}
41+
}

exercises/error_handling/errors2.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,16 @@
1919
// Execute `rustlings hint errors2` or use the `hint` watch subcommand for a
2020
// hint.
2121

22-
// I AM NOT DONE
23-
2422
use std::num::ParseIntError;
2523

2624
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
2725
let processing_fee = 1;
2826
let cost_per_item = 5;
2927
let qty = item_quantity.parse::<i32>();
30-
31-
Ok(qty * cost_per_item + processing_fee)
28+
match qty {
29+
Ok(v) => Ok(v * cost_per_item + processing_fee),
30+
Err(e) => Err(e),
31+
}
3232
}
3333

3434
#[cfg(test)]

exercises/error_handling/errors3.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,9 @@
77
// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a
88
// hint.
99

10-
// I AM NOT DONE
11-
1210
use std::num::ParseIntError;
1311

14-
fn main() {
12+
fn main() -> Result<(), ParseIntError> {
1513
let mut tokens = 100;
1614
let pretend_user_input = "8";
1715

@@ -23,6 +21,7 @@ fn main() {
2321
tokens -= cost;
2422
println!("You now have {} tokens.", tokens);
2523
}
24+
Ok(())
2625
}
2726

2827
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {

exercises/error_handling/errors4.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
// Execute `rustlings hint errors4` or use the `hint` watch subcommand for a
44
// hint.
55

6-
// I AM NOT DONE
7-
86
#[derive(PartialEq, Debug)]
97
struct PositiveNonzeroInteger(u64);
108

@@ -17,7 +15,13 @@ enum CreationError {
1715
impl PositiveNonzeroInteger {
1816
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
1917
// Hmm...? Why is this only returning an Ok value?
20-
Ok(PositiveNonzeroInteger(value as u64))
18+
if value < 0 {
19+
Err(CreationError::Negative)
20+
} else if value == 0 {
21+
Err(CreationError::Zero)
22+
} else {
23+
Ok(PositiveNonzeroInteger(value as u64))
24+
}
2125
}
2226
}
2327

@@ -29,4 +33,4 @@ fn test_creation() {
2933
PositiveNonzeroInteger::new(-10)
3034
);
3135
assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0));
32-
}
36+
}

exercises/error_handling/errors5.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,13 @@
2222
// Execute `rustlings hint errors5` or use the `hint` watch subcommand for a
2323
// hint.
2424

25-
// I AM NOT DONE
26-
2725
use std::error;
26+
use std::error::Error;
2827
use std::fmt;
2928
use std::num::ParseIntError;
3029

3130
// TODO: update the return type of `main()` to make this compile.
32-
fn main() -> Result<(), Box<dyn ???>> {
31+
fn main() -> Result<(), Box<dyn Error>> {
3332
let pretend_user_input = "42";
3433
let x: i64 = pretend_user_input.parse()?;
3534
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
@@ -68,4 +67,4 @@ impl fmt::Display for CreationError {
6867
}
6968
}
7069

71-
impl error::Error for CreationError {}
70+
impl error::Error for CreationError {}
Lines changed: 39 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
1-
// errors6.rs
1+
// errors5.rs
22
//
3-
// Using catch-all error types like `Box<dyn error::Error>` isn't recommended
4-
// for library code, where callers might want to make decisions based on the
5-
// error content, instead of printing it out or propagating it further. Here, we
6-
// define a custom error type to make it possible for callers to decide what to
7-
// do next when our function returns an error.
3+
// This program uses an altered version of the code from errors4.
84
//
9-
// Execute `rustlings hint errors6` or use the `hint` watch subcommand for a
5+
// This exercise uses some concepts that we won't get to until later in the
6+
// course, like `Box` and the `From` trait. It's not important to understand
7+
// them in detail right now, but you can read ahead if you like. For now, think
8+
// of the `Box<dyn ???>` type as an "I want anything that does ???" type, which,
9+
// given Rust's usual standards for runtime safety, should strike you as
10+
// somewhat lenient!
11+
//
12+
// In short, this particular use case for boxes is for when you want to own a
13+
// value and you care only that it is a type which implements a particular
14+
// trait. To do so, The Box is declared as of type Box<dyn Trait> where Trait is
15+
// the trait the compiler looks for on any value used in that context. For this
16+
// exercise, that context is the potential errors which can be returned in a
17+
// Result.
18+
//
19+
// What can we use to describe both errors? In other words, is there a trait
20+
// which both errors implement?
21+
//
22+
// Execute `rustlings hint errors5` or use the `hint` watch subcommand for a
1023
// hint.
1124

12-
// I AM NOT DONE
13-
25+
use std::error;
26+
use std::error::Error;
27+
use std::fmt;
1428
use std::num::ParseIntError;
1529

16-
// This is a custom error type that we will be using in `parse_pos_nonzero()`.
17-
#[derive(PartialEq, Debug)]
18-
enum ParsePosNonzeroError {
19-
Creation(CreationError),
20-
ParseInt(ParseIntError),
21-
}
22-
23-
impl ParsePosNonzeroError {
24-
fn from_creation(err: CreationError) -> ParsePosNonzeroError {
25-
ParsePosNonzeroError::Creation(err)
26-
}
27-
// TODO: add another error conversion function here.
28-
// fn from_parseint...
29-
}
30-
31-
fn parse_pos_nonzero(s: &str) -> Result<PositiveNonzeroInteger, ParsePosNonzeroError> {
32-
// TODO: change this to return an appropriate error instead of panicking
33-
// when `parse()` returns an error.
34-
let x: i64 = s.parse().unwrap();
35-
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
30+
// TODO: update the return type of `main()` to make this compile.
31+
fn main() -> Result<(), Box<dyn Error>> {
32+
let pretend_user_input = "42";
33+
let x: i64 = pretend_user_input.parse()?;
34+
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
35+
Ok(())
3636
}
3737

3838
// Don't change anything below this line.
@@ -56,39 +56,15 @@ impl PositiveNonzeroInteger {
5656
}
5757
}
5858

59-
#[cfg(test)]
60-
mod test {
61-
use super::*;
62-
63-
#[test]
64-
fn test_parse_error() {
65-
// We can't construct a ParseIntError, so we have to pattern match.
66-
assert!(matches!(
67-
parse_pos_nonzero("not a number"),
68-
Err(ParsePosNonzeroError::ParseInt(_))
69-
));
70-
}
71-
72-
#[test]
73-
fn test_negative() {
74-
assert_eq!(
75-
parse_pos_nonzero("-555"),
76-
Err(ParsePosNonzeroError::Creation(CreationError::Negative))
77-
);
78-
}
79-
80-
#[test]
81-
fn test_zero() {
82-
assert_eq!(
83-
parse_pos_nonzero("0"),
84-
Err(ParsePosNonzeroError::Creation(CreationError::Zero))
85-
);
86-
}
87-
88-
#[test]
89-
fn test_positive() {
90-
let x = PositiveNonzeroInteger::new(42);
91-
assert!(x.is_ok());
92-
assert_eq!(parse_pos_nonzero("42"), Ok(x.unwrap()));
59+
// This is required so that `CreationError` can implement `error::Error`.
60+
impl fmt::Display for CreationError {
61+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62+
let description = match *self {
63+
CreationError::Negative => "number is negative",
64+
CreationError::Zero => "number is zero",
65+
};
66+
f.write_str(description)
9367
}
9468
}
69+
70+
impl error::Error for CreationError {}

exercises/generics/generics1.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,8 @@
66
// Execute `rustlings hint generics1` or use the `hint` watch subcommand for a
77
// hint.
88

9-
// I AM NOT DONE
109

1110
fn main() {
12-
let mut shopping_list: Vec<?> = Vec::new();
11+
let mut shopping_list = Vec::new();
1312
shopping_list.push("milk");
1413
}

0 commit comments

Comments
 (0)