🚧 temp save

This commit is contained in:
lanzy 2024-03-23 19:12:35 +08:00
parent 9099bdcea5
commit a513d90cff
18 changed files with 119 additions and 51 deletions

View File

@ -12,8 +12,6 @@
// //
// Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
use std::borrow::Cow; use std::borrow::Cow;
fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> { fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> {

View File

@ -8,7 +8,6 @@
// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a // Execute `rustlings hint threads1` or use the `hint` watch subcommand for a
// hint. // hint.
// I AM NOT DONE
use std::thread; use std::thread;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@ -27,6 +26,7 @@ fn main() {
let mut results: Vec<u128> = vec![]; let mut results: Vec<u128> = vec![];
for handle in handles { for handle in handles {
// TODO: a struct is returned from thread::spawn, can you use it? // TODO: a struct is returned from thread::spawn, can you use it?
results.push(handle.join().unwrap());
} }
if results.len() != 10 { if results.len() != 10 {

View File

@ -7,9 +7,9 @@
// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a // Execute `rustlings hint threads2` or use the `hint` watch subcommand for a
// hint. // hint.
// I AM NOT DONE
use std::sync::Arc; use std::borrow::BorrowMut;
use std::sync::{Arc, Mutex};
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
@ -18,14 +18,16 @@ 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 mut handles = vec![]; let mut handles = vec![];
for _ in 0..10 { for _ in 0..10 {
let status_shared = Arc::clone(&status); let status_shared = Arc::clone(&status);
let handle = thread::spawn(move || { let handle = thread::spawn(move || {
thread::sleep(Duration::from_millis(250)); thread::sleep(Duration::from_millis(250));
// TODO: You must take an action before you update a shared value // TODO: You must take an action before you update a shared value
status_shared.jobs_completed += 1; status_shared.lock().unwrap().jobs_completed += 1;
// status_shared.borrow_mut().jobs_completed += 1;
// status_shared.jobs_completed += 1;
}); });
handles.push(handle); handles.push(handle);
} }
@ -34,6 +36,6 @@ fn main() {
// TODO: Print the value of the JobStatus.jobs_completed. Did you notice // TODO: Print the value of the JobStatus.jobs_completed. Did you notice
// anything interesting in the output? Do you have to 'join' on all the // anything interesting in the output? Do you have to 'join' on all the
// handles? // handles?
println!("jobs completed {}", ???); println!("jobs completed {}", status.lock().unwrap().jobs_completed);
} }
} }

View File

@ -3,10 +3,8 @@
// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a // Execute `rustlings hint threads3` or use the `hint` watch subcommand for a
// hint. // hint.
// I AM NOT DONE
use std::sync::mpsc; use std::sync::mpsc;
use std::sync::Arc;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
@ -27,18 +25,19 @@ impl Queue {
} }
fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () { fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {
let tx2 = tx.clone();
thread::spawn(move || { thread::spawn(move || {
for val in q.first_half { for val in q.first_half {
println!("sending {:?}", val); println!("sending {:?}", val);
tx.send(val).unwrap(); tx.clone().send(val).unwrap();
thread::sleep(Duration::from_secs(1)); thread::sleep(Duration::from_secs(1));
} }
}); });
thread::spawn(move || { thread::spawn( move|| {
for val in q.second_half { for val in q.second_half {
println!("sending {:?}", val); println!("sending {:?}", val);
tx.send(val).unwrap(); tx2.clone().send(val).unwrap();
thread::sleep(Duration::from_secs(1)); thread::sleep(Duration::from_secs(1));
} }
}); });

View File

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

View File

@ -3,14 +3,14 @@
// Execute `rustlings hint macros2` or use the `hint` watch subcommand for a // Execute `rustlings hint macros2` or use the `hint` watch subcommand for a
// hint. // 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

@ -5,9 +5,9 @@
// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a // Execute `rustlings hint macros3` or use the `hint` watch subcommand for a
// hint. // 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

@ -3,13 +3,12 @@
// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a // Execute `rustlings hint macros4` or use the `hint` watch subcommand for a
// hint. // 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);
} }

7
exercises/22_clippy/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "clippy3"
version = "0.0.1"

View File

@ -0,0 +1,7 @@
[package]
name = "clippy3"
version = "0.0.1"
edition = "2021"
[[bin]]
name = "clippy3"
path = "clippy3.rs"

View File

@ -9,12 +9,10 @@
// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a // Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a
// hint. // hint.
// I AM NOT DONE
use std::f32; use std::f32;
fn main() { fn main() {
let pi = 3.14f32; let pi = f32::consts::PI;
let radius = 5.00f32; let radius = 5.00f32;
let area = pi * f32::powi(radius, 2); let area = pi * f32::powi(radius, 2);

View File

@ -3,12 +3,11 @@
// Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a // Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a
// hint. // 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

@ -3,28 +3,30 @@
// 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.
// No hints. // No hints.
// 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_some() {
my_option.unwrap(); println!("There's something!");
} else {
println!("There's nothing!");
} }
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); vec![1, 2, 3, 4, 5].resize(0, 5);
println!("This Vec is empty, see? {:?}", my_empty_vec); println!("This Vec is empty, see? {:?}", ());
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; // value_a = 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

@ -9,23 +9,31 @@
// I AM NOT DONE // I AM NOT DONE
use std::ops::Mul;
// 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>(arg: &mut T)
where T: for<'a> AsMut<&'a mut Box<u32>> + for<'a> Mul<&'a mut T, Output = T>// + std::ops::MulAssign<&mut Box<u32>>
{
// TODO: Implement the function body. // TODO: Implement the function body.
??? *arg = (*arg) * arg;
} }
#[cfg(test)] #[cfg(test)]

View File

@ -24,7 +24,6 @@ impl Default for Person {
} }
} }
// Your task is to complete this implementation in order for the line `let p1 = // Your task is to complete this implementation in order for the line `let p1 =
// Person::from("Mark,20")` to compile. Please note that you'll need to parse the // Person::from("Mark,20")` to compile. Please note that you'll need to parse the
// age component into a `usize` with something like `"4".parse::<usize>()`. The // age component into a `usize` with something like `"4".parse::<usize>()`. The
@ -41,10 +40,24 @@ impl Default for Person {
// If while parsing the age, something goes wrong, then return the default of // If while parsing the age, something goes wrong, then return the default of
// Person Otherwise, then return an instantiated Person object with the results // Person 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.len() == 0 {
return Person::default();
}
let fields = s.split(',').collect::<Vec<&str>>();
if fields.len() != 2 {
return Person::default();
}
let name = fields[0].trim().to_string();
if name.len() == 0 {
return Person::default();
}
match fields[1].trim().parse::<usize>() {
Err(_) => Person::default(),
Ok(age) => Person { name, age },
}
}
} }
fn main() { fn main() {

View File

@ -31,8 +31,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
// 2. Split the given string on the commas present in it // 2. Split the given string on the commas present in it
@ -52,6 +50,22 @@ 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.len() == 0 {
return Err(ParsePersonError::Empty);
}
let fields = s.split(',').collect::<Vec<&str>>();
if fields.len() != 2 {
return Err(ParsePersonError::BadLen);
}
let name = fields[0].trim().to_string();
if name.len() == 0 {
return Err(ParsePersonError::NoName);
}
let age = fields[1].trim().parse::<usize>().map_err(ParsePersonError::ParseInt)?;
Ok(Person{
name,
age,
})
} }
} }

View File

@ -27,8 +27,6 @@ enum IntoColorError {
IntConversion, IntConversion,
} }
// I AM NOT DONE
// Your task is to complete this implementation and return an Ok result of inner // Your task is to complete this implementation and return an Ok result of inner
// type Color. You need to create an implementation for a tuple of three // type Color. You need to create an implementation for a tuple of three
// integers, an array of three integers, and a slice of integers. // integers, an array of three integers, and a slice of integers.
@ -37,17 +35,35 @@ enum IntoColorError {
// time, but the slice implementation needs to check the slice length! Also note // time, but the slice implementation needs to check the slice length! Also note
// that correct RGB color values must be integers in the 0..=255 range. // that correct RGB color values must be integers in the 0..=255 range.
fn convert_to_u8<T> (value: T) -> Result<u8, IntoColorError>
where T: TryInto<u8>
{
Ok(value.try_into().or(Err(IntoColorError::IntConversion))?)
}
// Tuple implementation // Tuple implementation
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> {
Ok(Color {
red: convert_to_u8(tuple.0)?,
green: convert_to_u8(tuple.1)?,
blue: convert_to_u8(tuple.2)?,
})
} }
} }
// Array implementation // Array implementation
impl TryFrom<[i16; 3]> for Color { impl<T> TryFrom<[T; 3]> for Color
where T: TryInto<u8> + Copy
{
type Error = IntoColorError; type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> { fn try_from(arr: [T; 3]) -> Result<Self, Self::Error> {
Ok(Color {
red: convert_to_u8(arr[0])?,
green: convert_to_u8(arr[1])?,
blue: convert_to_u8(arr[2])?,
})
} }
} }
@ -55,6 +71,14 @@ 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(IntoColorError::BadLen);
}
Ok(Color {
red: convert_to_u8(slice[0])?,
green: convert_to_u8(slice[1])?,
blue: convert_to_u8(slice[2])?,
})
} }
} }

View File

@ -10,11 +10,10 @@
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a // Execute `rustlings hint using_as` or use the `hint` watch subcommand for a
// hint. // 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() {