complit!!

This commit is contained in:
tab 2020-05-18 23:19:43 +08:00
parent 0babb9faf7
commit 9381dc4ed3
6 changed files with 40 additions and 16 deletions

View file

@ -2,16 +2,15 @@
// Read more about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html // Read more about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html
// and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. // and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively.
// I AM NOT DONE
// Obtain the number of bytes (not characters) in the given argument // Obtain the number of bytes (not characters) in the given argument
// Add the AsRef trait appropriately as a trait bound // Add the AsRef trait appropriately as a trait bound
fn byte_counter<T>(arg: T) -> usize { fn byte_counter<T: AsRef<str>>(arg: T) -> usize {
arg.as_ref().as_bytes().len() arg.as_ref().as_bytes().len()
} }
// Obtain the number of characters (not bytes) in the given argument // Obtain the number of characters (not bytes) in the given argument
// Add the AsRef trait appropriately as a trait bound // Add the AsRef trait appropriately as a trait bound
fn char_counter<T>(arg: T) -> usize { fn char_counter<T: AsRef<str>>(arg: T) -> usize {
arg.as_ref().chars().count() arg.as_ref().chars().count()
} }

View file

@ -18,7 +18,6 @@ impl Default for Person {
} }
} }
// I AM NOT DONE
// Your task is to complete this implementation // Your task is to complete this implementation
// in order for the line `let p = Person::from("Mark,20")` to compile // in order for the line `let p = Person::from("Mark,20")` to compile
// Please note that you'll need to parse the age component into a `usize` // Please note that you'll need to parse the age component into a `usize`
@ -35,6 +34,16 @@ impl Default for Person {
// Otherwise, then return an instantiated Person object with the results // Otherwise, then return an instantiated Person object with the results
impl From<&str> for Person { impl From<&str> for Person {
fn from(s: &str) -> Person { fn from(s: &str) -> Person {
let v: Vec<&str> = s.split(',').collect();
if v.len() < 2 {
return Person::default();
}
let age = v[1].parse();
if v[0].is_empty() || age.is_err() {
Person::default()
} else {
Person{name: v[0].to_string(), age: age.unwrap()}
}
} }
} }

View file

@ -10,7 +10,6 @@ struct Person {
age: usize, age: usize,
} }
// I AM NOT DONE
// Steps: // Steps:
// 1. If the length of the provided string is 0, then return an error // 1. If the length of the provided string is 0, then return an error
// 2. Split the given string on the commas present in it // 2. Split the given string on the commas present in it
@ -22,6 +21,16 @@ struct Person {
impl FromStr for Person { impl FromStr for Person {
type Err = String; type Err = String;
fn from_str(s: &str) -> Result<Person, Self::Err> { fn from_str(s: &str) -> Result<Person, Self::Err> {
let v: Vec<&str> = s.split(",").collect();
if v.len() < 2 {
return Err("need to args".to_string());
}
let age = v[1].parse();
if v[0].is_empty() || age.is_err() {
Err("wrong".to_string())
} else {
Ok(Person{name: v[0].to_string(), age: age.unwrap()})
}
} }
} }
@ -82,4 +91,4 @@ mod tests {
",one".parse::<Person>().unwrap(); ",one".parse::<Person>().unwrap();
} }
} }

View file

@ -10,7 +10,6 @@ struct Person {
age: usize, age: usize,
} }
// I AM NOT DONE
// Your task is to complete this implementation // Your task is to complete this implementation
// in order for the line `let p = Person::try_from("Mark,20")` to compile // in order for the line `let p = Person::try_from("Mark,20")` to compile
// and return an Ok result of inner type Person. // and return an Ok result of inner type Person.
@ -29,6 +28,16 @@ struct Person {
impl TryFrom<&str> for Person { impl TryFrom<&str> for Person {
type Error = String; type Error = String;
fn try_from(s: &str) -> Result<Self, Self::Error> { fn try_from(s: &str) -> Result<Self, Self::Error> {
let v: Vec<&str> = s.split(",").collect();
if v.len() < 2 {
return Err("need to args".to_string());
}
let age = v[1].parse();
if v[0].is_empty() || age.is_err() {
Err("wrong".to_string())
} else {
Ok(Person{name: v[0].to_string(), age: age.unwrap()})
}
} }
} }
@ -99,4 +108,4 @@ mod tests {
fn test_missing_name_and_invalid_age() { fn test_missing_name_and_invalid_age() {
let _: Person = ",one".try_into().unwrap(); let _: Person = ",one".try_into().unwrap();
} }
} }

View file

@ -2,16 +2,15 @@
// Please note that the `as` operator is not only used when type casting. // Please note that the `as` operator is not only used when type casting.
// It also helps with renaming imports. // It also helps with renaming imports.
// I AM NOT DONE
// The goal is to make sure that the division does not fail to compile // The goal is to make sure that the division does not fail to compile
fn average(values: &[f64]) -> f64 { fn average(values: &[f64]) -> f64 {
let total = values let total = values
.iter() .iter()
.fold(0.0, |a, b| a + b); .fold(0.0, |a, b| a + b);
total / values.len() total / values.len() as f64
} }
fn main() { fn main() {
let values = [3.5, 0.3, 13.0, 11.7]; let values = [3.5, 0.3, 13.0, 11.7];
println!("{}", average(&values)); println!("{}", average(&values));
} }

View file

@ -5,9 +5,8 @@
// of "waiting..." and the program ends without timing out when running, // of "waiting..." and the program ends without timing out when running,
// you've got it :) // you've got it :)
// I AM NOT DONE
use std::sync::Arc; use std::sync::Arc;
use std::sync::Mutex;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
@ -16,15 +15,15 @@ struct JobStatus {
} }
fn main() { fn main() {
let status = Arc::new(JobStatus { jobs_completed: 0 }); let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let status_shared = status.clone(); let status_shared = status.clone();
thread::spawn(move || { thread::spawn(move || {
for _ in 0..10 { for _ in 0..10 {
thread::sleep(Duration::from_millis(250)); thread::sleep(Duration::from_millis(250));
status_shared.jobs_completed += 1; status_shared.lock().unwrap().jobs_completed += 1;
} }
}); });
while status.jobs_completed < 10 { while status.lock().unwrap().jobs_completed < 10 {
println!("waiting... "); println!("waiting... ");
thread::sleep(Duration::from_millis(500)); thread::sleep(Duration::from_millis(500));
} }