mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-07 11:19:18 +00:00
added
This commit is contained in:
parent
c2de94d277
commit
ef0e19b5c1
5
.vscode/extensions.json
vendored
Normal file
5
.vscode/extensions.json
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"recommendations": [
|
||||||
|
"rust-lang.rust-analyzer"
|
||||||
|
]
|
||||||
|
}
|
||||||
@ -8,13 +8,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);
|
||||||
|
|||||||
@ -3,12 +3,10 @@
|
|||||||
// 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 {
|
while let Some(x) = option {
|
||||||
res += x;
|
res += x;
|
||||||
}
|
}
|
||||||
println!("{}", res);
|
println!("{}", res);
|
||||||
|
|||||||
@ -3,28 +3,21 @@
|
|||||||
// 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() {
|
|
||||||
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);
|
println!("This Vec is empty, see? {:?}", vec![1,2,3,4,5].resize(0, 0));
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,25 +7,25 @@
|
|||||||
// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
use std::ops::Mul;
|
||||||
|
|
||||||
// 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: 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.
|
||||||
// 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: AsRef<str>>(arg: T) -> usize {
|
||||||
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: AsMut<u32> {
|
||||||
// TODO: Implement the function body.
|
// TODO: Implementrhs the function body.
|
||||||
???
|
let x = arg.as_mut();
|
||||||
|
*x = x.mul(*x);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@ -40,10 +40,25 @@ 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 split_s = s.split(",");
|
||||||
|
let split_vec: Vec<&str> = split_s.collect();
|
||||||
|
if split_vec.len() < 2 {
|
||||||
|
return Person::default();
|
||||||
|
};
|
||||||
|
let name = split_vec[0].to_string();
|
||||||
|
if name.len() == 0 {
|
||||||
|
return Person::default();
|
||||||
|
};
|
||||||
|
let age: Result<usize, _> = split_vec[1].parse();
|
||||||
|
match age {
|
||||||
|
Ok(a) => Person { name, age: a },
|
||||||
|
Err(a) => Person::default()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -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 split_vec: Vec<&str> = s.split(",").collect();
|
||||||
|
if split_vec.len() != 2 {
|
||||||
|
return Err(ParsePersonError::BadLen);
|
||||||
|
};
|
||||||
|
let name = split_vec[0];
|
||||||
|
if name.len() == 0 {
|
||||||
|
return Err(ParsePersonError::NoName);
|
||||||
|
}
|
||||||
|
let age: Result<usize, _> = split_vec[1].parse();
|
||||||
|
match age {
|
||||||
|
Ok(a) => Ok(Person{name: name.to_string(), age: a}),
|
||||||
|
Err(x) => Err(ParsePersonError::ParseInt(x))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -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.
|
||||||
@ -36,11 +34,22 @@ enum IntoColorError {
|
|||||||
// Note that the implementation for tuple and array will be checked at compile
|
// Note that the implementation for tuple and array will be checked at compile
|
||||||
// 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 valid_num(num: i16) -> bool {
|
||||||
|
num >= 0 && num <= 255
|
||||||
|
}
|
||||||
|
|
||||||
// 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> {
|
||||||
|
if !(valid_num(tuple.0) && valid_num(tuple.1) && valid_num(tuple.2)) {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
return Ok(Color{
|
||||||
|
red: tuple.0 as u8,
|
||||||
|
green: tuple.1 as u8,
|
||||||
|
blue: tuple.2 as u8
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -48,6 +57,17 @@ 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> {
|
||||||
|
if arr.len() != 3 {
|
||||||
|
return Err(IntoColorError::BadLen);
|
||||||
|
}
|
||||||
|
if !(valid_num(arr[0]) && valid_num(arr[1]) && valid_num(arr[2])) {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
return Ok(Color{
|
||||||
|
red: arr[0] as u8,
|
||||||
|
green: arr[1] as u8,
|
||||||
|
blue: arr[2] as u8
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,6 +75,17 @@ 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);
|
||||||
|
}
|
||||||
|
if !(valid_num(slice[0]) && valid_num(slice[1]) && valid_num(slice[2])) {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
return Ok(Color{
|
||||||
|
red: slice[0] as u8,
|
||||||
|
green: slice[1] as u8,
|
||||||
|
blue: slice[2] as u8
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -10,11 +10,9 @@
|
|||||||
// 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() {
|
||||||
|
|||||||
@ -3,8 +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 {
|
||||||
() => {
|
() => {
|
||||||
println!("Check out my macro!");
|
println!("Check out my macro!");
|
||||||
@ -12,5 +10,5 @@ macro_rules! my_macro {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
my_macro();
|
my_macro!();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,14 +3,12 @@
|
|||||||
// 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!();
|
||||||
|
}
|
||||||
@ -5,8 +5,7 @@
|
|||||||
// 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
|
#[macro_use]
|
||||||
|
|
||||||
mod macros {
|
mod macros {
|
||||||
macro_rules! my_macro {
|
macro_rules! my_macro {
|
||||||
() => {
|
() => {
|
||||||
|
|||||||
@ -3,13 +3,11 @@
|
|||||||
// 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);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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]> {
|
||||||
|
|||||||
@ -8,8 +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 +25,9 @@ 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?
|
||||||
|
if let Ok(x) = handle.join() {
|
||||||
|
results.push(x);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if results.len() != 10 {
|
if results.len() != 10 {
|
||||||
|
|||||||
@ -7,9 +7,8 @@
|
|||||||
// 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::sync::Arc;
|
||||||
|
use std::sync::Mutex;
|
||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@ -18,22 +17,23 @@ 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<Mutex<JobStatus>> = 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;
|
let mut job_status = status_shared.lock().unwrap();
|
||||||
|
job_status.jobs_completed += 1;
|
||||||
|
|
||||||
});
|
});
|
||||||
handles.push(handle);
|
handles.push(handle);
|
||||||
}
|
}
|
||||||
for handle in handles {
|
for handle in handles {
|
||||||
handle.join().unwrap();
|
|
||||||
// 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,8 +3,6 @@
|
|||||||
// 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::sync::Arc;
|
||||||
use std::thread;
|
use std::thread;
|
||||||
@ -31,10 +29,13 @@ fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {
|
|||||||
let qc1 = Arc::clone(&qc);
|
let qc1 = Arc::clone(&qc);
|
||||||
let qc2 = Arc::clone(&qc);
|
let qc2 = Arc::clone(&qc);
|
||||||
|
|
||||||
|
let tx1 = tx.clone();
|
||||||
|
let tx2 = tx.clone();
|
||||||
|
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
for val in &qc1.first_half {
|
for val in &qc1.first_half.clone() {
|
||||||
println!("sending {:?}", val);
|
println!("sending {:?}", val);
|
||||||
tx.send(*val).unwrap();
|
tx1.send(*val).unwrap();
|
||||||
thread::sleep(Duration::from_secs(1));
|
thread::sleep(Duration::from_secs(1));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -42,7 +43,7 @@ fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {
|
|||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
for val in &qc2.second_half {
|
for val in &qc2.second_half {
|
||||||
println!("sending {:?}", val);
|
println!("sending {:?}", val);
|
||||||
tx.send(*val).unwrap();
|
tx2.send(*val).unwrap();
|
||||||
thread::sleep(Duration::from_secs(1));
|
thread::sleep(Duration::from_secs(1));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user