Skip to content

Commit

Permalink
错误处理 测试 特性
Browse files Browse the repository at this point in the history
  • Loading branch information
davidxifeng committed Aug 6, 2022
1 parent 1c33e58 commit 7b2d6ed
Show file tree
Hide file tree
Showing 21 changed files with 85 additions and 81 deletions.
8 changes: 3 additions & 5 deletions rust/rustlings/exercises/error_handling/errors1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@
// 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.

// 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
Result::Err("`name` was empty; it must be nonempty.".to_string())
} else {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
}
}

Expand Down
12 changes: 9 additions & 3 deletions rust/rustlings/exercises/error_handling/errors2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,22 @@
// one is a lot shorter!
// 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>()?; // 简短的写法是使用?

// 冗长的写法; 前一种写法就很类似Maybe Monad了吧
let qty = item_quantity.parse::<i32>();
if let Ok(q) = qty {
Ok(q * cost_per_item + processing_fee)
} else {
qty
}

Ok(qty * cost_per_item + processing_fee)
// Ok(qty * cost_per_item + processing_fee)
}

#[cfg(test)]
Expand Down
7 changes: 4 additions & 3 deletions rust/rustlings/exercises/error_handling/errors3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@
// Why not? What should we do to fix it?
// 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<(), ParseIntError>{

let mut tokens = 100;
let pretend_user_input = "8";

Expand All @@ -20,6 +19,8 @@ fn main() {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}

Ok(())
}

pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
Expand Down
11 changes: 7 additions & 4 deletions rust/rustlings/exercises/error_handling/errors4.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// errors4.rs
// Execute `rustlings hint errors4` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);

Expand All @@ -14,8 +12,13 @@ enum CreationError {

impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
// 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::Negative)
} else {
Err(CreationError::Zero)
}
}
}

Expand Down
4 changes: 1 addition & 3 deletions rust/rustlings/exercises/error_handling/errors5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@

// Execute `rustlings hint errors5` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

use std::error;
use std::fmt;
use std::num::ParseIntError;

// 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 x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
Expand Down
23 changes: 12 additions & 11 deletions rust/rustlings/exercises/error_handling/errors6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,34 @@

// Execute `rustlings hint errors6` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

use std::num::ParseIntError;

// This is a custom error type that we will be using in `parse_pos_nonzero()`.
#[derive(PartialEq, Debug)]
enum ParsePosNonzeroError {
Creation(CreationError),
ParseInt(ParseIntError)
ParseInt(ParseIntError),
}

impl ParsePosNonzeroError {
fn from_creation(err: CreationError) -> ParsePosNonzeroError {
ParsePosNonzeroError::Creation(err)
}
// 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
// when `parse()` returns an error.
let x: i64 = s.parse().unwrap();
PositiveNonzeroInteger::new(x)
.map_err(ParsePosNonzeroError::from_creation)
let x = s.parse();
match x {
Ok(x) => PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation),
// 不知道这种写法是否为最优写法
Err(x) => Err(ParsePosNonzeroError::from_parseint(x))
}
}

// Don't change anything below this line.
Expand All @@ -53,7 +54,7 @@ impl PositiveNonzeroInteger {
match value {
x if x < 0 => Err(CreationError::Negative),
x if x == 0 => Err(CreationError::Zero),
x => Ok(PositiveNonzeroInteger(x as u64))
x => Ok(PositiveNonzeroInteger(x as u64)),
}
}
}
Expand Down
4 changes: 1 addition & 3 deletions rust/rustlings/exercises/generics/generics1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@

// Execute `rustlings hint generics1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

fn main() {
let mut shopping_list: Vec<?> = Vec::new();
let mut shopping_list: Vec<&str> = Vec::new();
shopping_list.push("milk");
}
11 changes: 5 additions & 6 deletions rust/rustlings/exercises/generics/generics2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@

// Execute `rustlings hint generics2` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

struct Wrapper {
value: u32,
struct Wrapper<T>{
value: T,
}

impl Wrapper {
pub fn new(value: u32) -> Self {
// 语法: 这里需要写两个泛型参数
impl<T> Wrapper<T> {
pub fn new(value: T) -> Self {
Wrapper { value }
}
}
Expand Down
2 changes: 1 addition & 1 deletion rust/rustlings/exercises/lifetimes/lifetimes1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

// I AM NOT DONE

fn longest(x: &str, y: &str) -> &str {
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
Expand Down
9 changes: 6 additions & 3 deletions rust/rustlings/exercises/options/options1.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// options1.rs
// Execute `rustlings hint options1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

// you can modify anything EXCEPT for this function's signature
fn print_number(maybe_number: Option<u16>) {
println!("printing: {}", maybe_number.unwrap());
Expand All @@ -14,7 +12,11 @@ fn print_number(maybe_number: Option<u16>) {
// TODO: Return an Option!
fn maybe_icecream(time_of_day: u16) -> Option<u16> {
// We use the 24-hour system here, so 10PM is a value of 22
???
if time_of_day < 22 {
Some(5)
} else {
None
}
}

#[cfg(test)]
Expand All @@ -32,6 +34,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 = icecreams.unwrap();
assert_eq!(icecreams, 5);
}
}
15 changes: 8 additions & 7 deletions rust/rustlings/exercises/options/options2.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
// options2.rs
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

fn main() {
let optional_word = Some(String::from("rustlings"));
// TODO: Make this an if let statement whose value is "Some" type
word = optional_word {
println!("The word is: {}", word);
if let word = optional_word {
println!("The word is: {}", word.unwrap());
} else {
println!("The optional word doesn't contain anything");
}
Expand All @@ -17,9 +15,12 @@ fn main() {
optional_integers_vec.push(Some(x));
}

// 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
integer = optional_integers_vec.pop() {
println!("current value: {}", integer);
while let Some(integer) = optional_integers_vec.pop() {
if let i = integer {
println!("current value: {}", i.unwrap());
}
}
}
6 changes: 3 additions & 3 deletions rust/rustlings/exercises/options/options3.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
// options3.rs
// Execute `rustlings hint options3` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

struct Point {
x: i32,
y: i32,
}

fn main() {
// 推测自然是只有堆上对象才需要如此处理
let y: Option<Point> = Some(Point { x: 100, y: 200 });

match y {
Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y),
// 使用ref表示仅借用,不移动; 不影响一个值是否匹配,只影响匹配方式: 借用还是move
Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y),
_ => println!("no match"),
}
y; // Fix without deleting this line.
Expand Down
11 changes: 5 additions & 6 deletions rust/rustlings/exercises/quiz3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,14 @@

// Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

pub struct ReportCard {
pub grade: f32,
pub struct ReportCard <T: std::fmt::Display>{
pub grade: T,
pub student_name: String,
pub student_age: u8,
}

impl ReportCard {
// 语法原来如此
impl <T: std::fmt::Display> ReportCard <T>{
pub fn print(&self) -> String {
format!("{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade)
Expand Down Expand Up @@ -50,7 +49,7 @@ mod tests {
fn generate_alphabetic_report_card() {
// TODO: Make sure to change the grade here after you finish the exercise.
let report_card = ReportCard {
grade: 2.1,
grade: "A+".to_string(),
student_name: "Gary Plotter".to_string(),
student_age: 11,
};
Expand Down
4 changes: 1 addition & 3 deletions rust/rustlings/exercises/tests/tests1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@
// pass! Make the test fail!
// Execute `rustlings hint tests1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

#[cfg(test)]
mod tests {
#[test]
fn you_can_assert() {
assert!();
assert!(true);
}
}
4 changes: 1 addition & 3 deletions rust/rustlings/exercises/tests/tests2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@
// pass! Make the test fail!
// Execute `rustlings hint tests2` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

#[cfg(test)]
mod tests {
#[test]
fn you_can_assert_eq() {
assert_eq!();
assert_eq!(true, true);
}
}
6 changes: 2 additions & 4 deletions rust/rustlings/exercises/tests/tests3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
// we expect to get when we call `is_even(5)`.
// Execute `rustlings hint tests3` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

pub fn is_even(num: i32) -> bool {
num % 2 == 0
}
Expand All @@ -16,11 +14,11 @@ mod tests {

#[test]
fn is_true_when_even() {
assert!();
assert!(is_even(2) == true);
}

#[test]
fn is_false_when_odd() {
assert!();
assert!(is_even(3) == false);
}
}
5 changes: 3 additions & 2 deletions rust/rustlings/exercises/traits/traits1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@
// implementing this trait.
// Execute `rustlings hint traits1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

trait AppendBar {
fn append_bar(self) -> Self;
}

impl AppendBar for String {
//Add your code here
fn append_bar(self) -> Self {
self + "Bar"
}
}

fn main() {
Expand Down
Loading

0 comments on commit 7b2d6ed

Please sign in to comment.