errors option move semantics

This commit is contained in:
zhihanz 2020-05-04 02:19:20 -07:00
parent 30286f3b20
commit 0df3cf8211
10 changed files with 28 additions and 39 deletions

View file

@ -6,14 +6,13 @@
// this function to have.
// Execute `rustlings hint errors1` for hints!
// 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.len() > 0 {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
} else {
// Empty names aren't allowed.
None
Err(format!("`name` was empty; it must be nonempty."))
}
}
@ -27,7 +26,7 @@ mod tests {
#[test]
fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!(
generate_nametag_text("Beyoncé".into()),
generate_nametag_text("Beyoncé".into()).ok(),
Some("Hi! My name is Beyoncé".into())
);
}

View file

@ -16,16 +16,15 @@
// There are at least two ways to implement this that are both correct-- but
// one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways.
// 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)
Ok(qty*cost_per_item + processing_fee)
}
#[cfg(test)]

View file

@ -4,7 +4,6 @@
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints!
// I AM NOT DONE
use std::num::ParseIntError;
@ -12,7 +11,7 @@ fn main() {
let mut tokens = 100;
let pretend_user_input = "8";
let cost = total_cost(pretend_user_input)?;
let cost = total_cost(pretend_user_input).expect("wrong num");
if cost > tokens {
println!("You can't afford that many!");

View file

@ -15,19 +15,18 @@
//
// Execute `rustlings hint errorsn` for hints :)
// I AM NOT DONE
use std::error;
use std::fmt;
use std::io;
// PositiveNonzeroInteger is a struct defined below the tests.
fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger, ???> {
fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger,Box<dyn error::Error>> {
let mut line = String::new();
b.read_line(&mut line);
let num: i64 = line.trim().parse();
let answer = PositiveNonzeroInteger::new(num);
answer
b.read_line(&mut line)?;
let num: i64 = line.trim().parse()?;
let answer = PositiveNonzeroInteger::new(num)?;
Ok(answer)
}
// This is a test helper function that turns a &str into a BufReader.

View file

@ -1,12 +1,11 @@
// move_semantics1.rs
// Make me compile! Execute `rustlings hint move_semantics1` for hints :)
// I AM NOT DONE
fn main() {
let vec0 = Vec::new();
let vec1 = fill_vec(vec0);
let mut vec1 = fill_vec(vec0);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
@ -15,7 +14,7 @@ fn main() {
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
fn fill_vec(vec: Vec<i32>) ->Vec<i32> {
let mut vec = vec;
vec.push(22);

View file

@ -2,12 +2,11 @@
// Make me compile without changing line 13!
// Execute `rustlings hint move_semantics2` for hints :)
// I AM NOT DONE
fn main() {
let vec0 = Vec::new();
let mut vec1 = fill_vec(vec0);
let mut vec1 = fill_vec(&vec0);
// Do not change the following line!
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);
@ -17,8 +16,8 @@ fn main() {
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
fn fill_vec(vec: &Vec<i32>) -> Vec<i32> {
let mut vec = vec.clone();
vec.push(22);
vec.push(44);

View file

@ -3,10 +3,9 @@
// (no lines with multiple semicolons necessary!)
// Execute `rustlings hint move_semantics3` for hints :)
// I AM NOT DONE
fn main() {
let vec0 = Vec::new();
let mut vec0 = Vec::new();
let mut vec1 = fill_vec(vec0);
@ -17,7 +16,7 @@ fn main() {
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
vec.push(22);
vec.push(44);
vec.push(66);

View file

@ -4,12 +4,10 @@
// freshly created vector from fill_vec to its caller.
// Execute `rustlings hint move_semantics4` for hints!
// I AM NOT DONE
fn main() {
let vec0 = Vec::new();
let mut vec1 = fill_vec(vec0);
let mut vec1 = fill_vec();
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
@ -20,7 +18,7 @@ fn main() {
// `fill_vec()` no longer take `vec: Vec<i32>` as argument
fn fill_vec() -> Vec<i32> {
let mut vec = vec;
let mut vec : Vec<i32> = Vec::new();
vec.push(22);
vec.push(44);

View file

@ -1,7 +1,6 @@
// option1.rs
// Make me compile! Execute `rustlings hint option1` for hints
// I AM NOT DONE
// you can modify anything EXCEPT for this function's sig
fn print_number(maybe_number: Option<u16>) {
@ -9,15 +8,15 @@ fn print_number(maybe_number: Option<u16>) {
}
fn main() {
print_number(13);
print_number(99);
print_number(Some(13));
print_number(Some(99));
let mut numbers: [Option<u16>; 5];
let mut numbers: [Option<u16>; 5] = Default::default();
for iter in 0..5 {
let number_to_add: u16 = {
((iter * 5) + 2) / (4 * 16)
};
numbers[iter] = number_to_add;
numbers[iter as usize] = Some(number_to_add);
}
}

View file

@ -1,12 +1,11 @@
// option2.rs
// Make me compile! Execute `rustlings hint option2` for hints
// I AM NOT DONE
fn main() {
let optional_value = Some(String::from("rustlings"));
// Make this an if let statement whose value is "Some" type
value = optional_value {
if let Some(value) = optional_value {
println!("the value of optional value is: {}", value);
} else {
println!("The optional value doesn't contain anything!");
@ -19,7 +18,7 @@ fn main() {
// 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
value = optional_values_vec.pop() {
println!("current value: {}", value);
while let Some(value) = optional_values_vec.pop() {
println!("current value: {}", value.unwrap());
}
}