This commit is contained in:
Dameng 2023-05-28 11:12:31 +00:00
parent afe0c311c9
commit 473102a7f2
18 changed files with 126 additions and 48 deletions

View File

@ -6,15 +6,14 @@
// check clippy's suggestions from the output to solve the exercise. // check clippy's suggestions from the output to solve the exercise.
// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
use std::f32; use std::f32;
fn main() { fn main() {
let pi = 3.14f32; let pp :f32= f32::consts::PI;
let radius = 5.00f32; let radius = 5.00f32;
let area = pi * f32::powi(radius, 2); let area = pp * f32::powi(radius, 2);
println!( println!(
"The area of a circle with radius {:.2} is {:.5}!", "The area of a circle with radius {:.2} is {:.5}!",

View File

@ -1,13 +1,12 @@
// clippy2.rs // clippy2.rs
// Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() { fn main() {
let mut res = 42; let mut res = 42;
let option = Some(12); let option = Some(12);
for x in option { if let Some(x) = option {
res += x; res+=x;
} }
println!("{}", res); println!("{}", res);
} }

View File

@ -1,28 +1,27 @@
// clippy3.rs // clippy3.rs
// Here's a couple more easy Clippy fixes, so you can see its utility. // Here's a couple more easy Clippy fixes, so you can see its utility.
// I AM NOT DONE
#[allow(unused_variables, unused_assignments)] #[allow(unused_variables, unused_assignments)]
fn main() { fn main() {
let my_option: Option<()> = None; let my_option: Option<()> = None;
if my_option.is_none() { if my_option.is_none() {
my_option.unwrap();
} }
let my_arr = &[ let my_arr = &[
-1, -2, -3 -1, -2, -3,
-4, -5, -6 -4, -5, -6
]; ];
println!("My array! Here it is: {:?}", my_arr); println!("My array! Here it is: {:?}", my_arr);
let my_empty_vec = vec![1, 2, 3, 4, 5].resize(0, 5); let mut my_empty_vec = vec![1, 2, 3, 4, 5];
my_empty_vec.clear();
println!("This Vec is empty, see? {:?}", my_empty_vec); println!("This Vec is empty, see? {:?}", my_empty_vec);
let mut value_a = 45; let mut value_a = 45;
let mut value_b = 66; let mut value_b = 66;
// Let's swap these two! // Let's swap these two!
value_a = value_b; std::mem::swap(&mut value_a,& mut value_b);
value_b = value_a;
println!("value a: {}; value b: {}", value_a, value_b); println!("value a: {}; value b: {}", value_a, value_b);
} }

View File

@ -3,25 +3,26 @@
// and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. // and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively.
// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a hint.
// 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.
// TODO: Add the AsRef trait appropriately as a trait bound. // TODO: Add the AsRef trait appropriately as a trait bound.
fn byte_counter<T>(arg: T) -> usize { fn byte_counter<T>(arg: T) -> usize where T:AsRef<str> {
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.
// TODO: Add the AsRef trait appropriately as a trait bound. // TODO: Add the AsRef trait appropriately as a trait bound.
fn char_counter<T>(arg: T) -> usize { fn char_counter<T>(arg: T) -> usize where T:AsRef<str>{
arg.as_ref().chars().count() arg.as_ref().chars().count()
} }
// Squares a number using as_mut(). // Squares a number using as_mut().
// TODO: Add the appropriate trait bound. // TODO: Add the appropriate trait bound.
fn num_sq<T>(arg: &mut T) { fn num_sq<T:AsMut<u32>>(arg: &mut T) {
// TODO: Implement the function body. // TODO: Implement the function body.
??? let mut number = arg.as_mut();
*number = (*number) * (*number);
} }
#[cfg(test)] #[cfg(test)]

View File

@ -35,10 +35,29 @@ impl Default for Person {
// If while parsing the age, something goes wrong, then return the default of Person // If while parsing the age, something goes wrong, then return the default of Person
// Otherwise, then return an instantiated Person object with the results // Otherwise, then return an instantiated Person object with the results
// I AM NOT DONE
impl From<&str> for Person { impl From<&str> for Person {
fn from(s: &str) -> Person { fn from(s: &str) -> Person {
if s.is_empty() {
return Person::default();
}
let parts :Vec<&str>= s.split(',').collect();
if parts.len()!=2{
return Person::default()
}
if parts[0].is_empty(){
return Person::default();
}
let ageResult = parts.get(1).unwrap_or(&"").to_string().parse::<usize>();
if let Ok(age) = ageResult {
return Person{
name:parts[0].to_string(),
age:age
}
}else
{
return Person::default();
}
} }
} }

View File

@ -28,7 +28,6 @@ enum ParsePersonError {
ParseInt(ParseIntError), ParseInt(ParseIntError),
} }
// I AM NOT DONE
// Steps: // Steps:
// 1. If the length of the provided string is 0, an error should be returned // 1. If the length of the provided string is 0, an error should be returned
@ -46,6 +45,30 @@ enum ParsePersonError {
impl FromStr for Person { impl FromStr for Person {
type Err = ParsePersonError; type Err = ParsePersonError;
fn from_str(s: &str) -> Result<Person, Self::Err> { fn from_str(s: &str) -> Result<Person, Self::Err> {
if s.is_empty(){
return Err(ParsePersonError::Empty)
}
let parts:Vec<&str> = s.split(',').collect();
if parts.len() != 2{
return Err(ParsePersonError::BadLen)
}
if parts[0].is_empty(){
return Err( ParsePersonError::NoName)
}
match parts[1].parse::<usize>(){
Ok(age)=>
{
Ok(Person{
name:parts[0].to_string(),
age:age
})
},
Err(err)=>{
Err(ParsePersonError::ParseInt(err))
}
}
} }
} }

View File

@ -23,8 +23,6 @@ enum IntoColorError {
IntConversion, IntConversion,
} }
// I AM NOT DONE
// Your task is to complete this implementation // Your task is to complete this implementation
// and return an Ok result of inner type Color. // and return an Ok result of inner type Color.
// You need to create an implementation for a tuple of three integers, // You need to create an implementation for a tuple of three integers,
@ -38,6 +36,14 @@ enum IntoColorError {
impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError; type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> { fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
let r = tuple.0.try_into().map_err(|_|Self::Error::IntConversion)?;
let g = tuple.1.try_into().map_err(|_|Self::Error::IntConversion)?;
let b = tuple.2.try_into().map_err(|_|Self::Error::IntConversion)?;
Ok(Color {
red:r,
green:g,
blue:b
})
} }
} }
@ -45,6 +51,14 @@ impl TryFrom<(i16, i16, i16)> for Color {
impl TryFrom<[i16; 3]> for Color { impl TryFrom<[i16; 3]> for Color {
type Error = IntoColorError; type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> { fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
let r = arr[0].try_into().map_err(|_|Self::Error::IntConversion)?;
let g = arr[1].try_into().map_err(|_|Self::Error::IntConversion)?;
let b = arr[2].try_into().map_err(|_|Self::Error::IntConversion)?;
Ok(Color {
red:r,
green:g,
blue:b
})
} }
} }
@ -52,6 +66,18 @@ impl TryFrom<[i16; 3]> for Color {
impl TryFrom<&[i16]> for Color { impl TryFrom<&[i16]> for Color {
type Error = IntoColorError; type Error = IntoColorError;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> { fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
if slice.len()!=3 {
return Err(Self::Error::BadLen)
}
let r = slice[0].try_into().map_err(|_|Self::Error::IntConversion)?;
let g = slice[1].try_into().map_err(|_|Self::Error::IntConversion)?;
let b = slice[2].try_into().map_err(|_|Self::Error::IntConversion)?;
Ok(Color {
red:r,
green:g,
blue:b
})
} }
} }

View File

@ -6,11 +6,10 @@
// and returns the proper type. // and returns the proper type.
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint using_as` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn average(values: &[f64]) -> f64 { fn average(values: &[f64]) -> f64 {
let total = values.iter().sum::<f64>(); let total= values.iter().sum::<f64>();
total / values.len() total / values.len() as f64
} }
fn main() { fn main() {

View File

@ -1,7 +1,6 @@
// macros1.rs // macros1.rs
// Execute `rustlings hint macros1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint macros1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
macro_rules! my_macro { macro_rules! my_macro {
() => { () => {
@ -10,5 +9,5 @@ macro_rules! my_macro {
} }
fn main() { fn main() {
my_macro(); my_macro!();
} }

View File

@ -1,14 +1,13 @@
// macros2.rs // macros2.rs
// Execute `rustlings hint macros2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint macros2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
my_macro!();
}
macro_rules! my_macro { macro_rules! my_macro {
() => { () => {
println!("Check out my macro!"); println!("Check out my macro!");
}; };
} }
fn main() {
my_macro!();
}

View File

@ -2,9 +2,9 @@
// Make me compile, without taking the macro out of the module! // Make me compile, without taking the macro out of the module!
// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint macros3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
mod macros { mod macros {
#[macro_export]
macro_rules! my_macro { macro_rules! my_macro {
() => { () => {
println!("Check out my macro!"); println!("Check out my macro!");

View File

@ -1,16 +1,15 @@
// macros4.rs // macros4.rs
// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint macros4` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[rustfmt::skip] #[rustfmt::skip]
macro_rules! my_macro { macro_rules! my_macro {
() => { () => {
println!("Check out my macro!"); println!("Check out my macro!");
} };
($val:expr) => { ($val:expr) => {
println!("Look at this other macro: {}", $val); println!("Look at this other macro: {}", $val);
} };
} }
fn main() { fn main() {

View File

@ -18,21 +18,21 @@
// where the second TODO comment is. Try not to create any copies of the `numbers` Vec! // where the second TODO comment is. Try not to create any copies of the `numbers` Vec!
// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#![forbid(unused_imports)] // Do not change this, (or the next) line. #![forbid(unused_imports)] // Do not change this, (or the next) line.
use std::sync::Arc; use std::sync::Arc;
use std::thread; use std::thread;
use std::sync::Mutex;
fn main() { fn main() {
let numbers: Vec<_> = (0..100u32).collect(); let numbers: Vec<_> = (0..100u32).collect();
let shared_numbers = // TODO let shared_numbers = Arc::new(Mutex::new(numbers));// TODO
let mut joinhandles = Vec::new(); let mut joinhandles = Vec::new();
for offset in 0..8 { for offset in 0..8 {
let child_numbers = // TODO let child_numbers = shared_numbers.clone();// TODO
joinhandles.push(thread::spawn(move || { joinhandles.push(thread::spawn(move || {
let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); let sum: u32 = child_numbers.lock().unwrap().iter().filter(|&&n| n % 8 == offset).sum();
println!("Sum of offset {} is {}", offset, sum); println!("Sum of offset {} is {}", offset, sum);
})); }));
} }

View File

@ -16,11 +16,10 @@
// //
// Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub enum List { pub enum List {
Cons(i32, List), Cons(i32, Box<List>),
Nil, Nil,
} }
@ -33,11 +32,11 @@ fn main() {
} }
pub fn create_empty_list() -> List { pub fn create_empty_list() -> List {
todo!() List::Nil
} }
pub fn create_non_empty_list() -> List { pub fn create_non_empty_list() -> List {
todo!() List::Cons(1, Box::new(List::Nil))
} }
#[cfg(test)] #[cfg(test)]

View File

@ -8,7 +8,6 @@
// This exercise is meant to show you what to expect when passing data to Cow. // This exercise is meant to show you what to expect when passing data to Cow.
// Fix the unit tests by checking for Cow::Owned(_) and Cow::Borrowed(_) at the TODO markers. // Fix the unit tests by checking for Cow::Owned(_) and Cow::Borrowed(_) at the TODO markers.
// I AM NOT DONE
use std::borrow::Cow; use std::borrow::Cow;
@ -45,6 +44,11 @@ mod tests {
let mut input = Cow::from(&slice[..]); let mut input = Cow::from(&slice[..]);
match abs_all(&mut input) { match abs_all(&mut input) {
// TODO // TODO
Cow::Borrowed(x)=>{
Ok(())
},
_=> Err(""),
} }
} }
@ -58,6 +62,10 @@ mod tests {
let mut input = Cow::from(slice); let mut input = Cow::from(slice);
match abs_all(&mut input) { match abs_all(&mut input) {
// TODO // TODO
Cow::Borrowed(x)=>{
Err("")
},
_=> Ok(()),
} }
} }
@ -70,6 +78,10 @@ mod tests {
let mut input = Cow::from(slice); let mut input = Cow::from(slice);
match abs_all(&mut input) { match abs_all(&mut input) {
// TODO // TODO
Cow::Borrowed(x)=>{
Ok(())
},
_=> Ok(()),
} }
} }
} }

View File

@ -5,7 +5,6 @@
// Make this code compile by using the proper Rc primitives to express that the sun has multiple owners. // Make this code compile by using the proper Rc primitives to express that the sun has multiple owners.
// I AM NOT DONE
use std::rc::Rc; use std::rc::Rc;
@ -55,17 +54,17 @@ fn main() {
jupiter.details(); jupiter.details();
// TODO // TODO
let saturn = Planet::Saturn(Rc::new(Sun {})); let saturn = Planet::Saturn(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 7 references println!("reference count = {}", Rc::strong_count(&sun)); // 7 references
saturn.details(); saturn.details();
// TODO // TODO
let uranus = Planet::Uranus(Rc::new(Sun {})); let uranus = Planet::Uranus(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 8 references println!("reference count = {}", Rc::strong_count(&sun)); // 8 references
uranus.details(); uranus.details();
// TODO // TODO
let neptune = Planet::Neptune(Rc::new(Sun {})); let neptune = Planet::Neptune(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 9 references println!("reference count = {}", Rc::strong_count(&sun)); // 9 references
neptune.details(); neptune.details();
@ -87,12 +86,15 @@ fn main() {
println!("reference count = {}", Rc::strong_count(&sun)); // 4 references println!("reference count = {}", Rc::strong_count(&sun)); // 4 references
// TODO // TODO
drop(earth);
println!("reference count = {}", Rc::strong_count(&sun)); // 3 references println!("reference count = {}", Rc::strong_count(&sun)); // 3 references
// TODO // TODO
drop(venus);
println!("reference count = {}", Rc::strong_count(&sun)); // 2 references println!("reference count = {}", Rc::strong_count(&sun)); // 2 references
// TODO // TODO
drop(mercury);
println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference
assert_eq!(Rc::strong_count(&sun), 1); assert_eq!(Rc::strong_count(&sun), 1);

BIN
exercises/threads/threads3 Executable file

Binary file not shown.

View File

@ -60,6 +60,9 @@ fn main() {
for received in rx { for received in rx {
println!("Got: {}", received); println!("Got: {}", received);
total_received += 1; total_received += 1;
if total_received >= queue_length{
break;
}
} }
println!("total numbers received: {}", total_received); println!("total numbers received: {}", total_received);