mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-12 13:49:19 +00:00
updates
This commit is contained in:
parent
70423b9bef
commit
ecd727a33d
@ -6,12 +6,10 @@
|
|||||||
// 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` for hints :)
|
// Execute `rustlings hint clippy1` for hints :)
|
||||||
|
|
||||||
// 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);
|
||||||
|
|||||||
@ -1,12 +1,10 @@
|
|||||||
// clippy2.rs
|
// clippy2.rs
|
||||||
// Make me compile! Execute `rustlings hint clippy2` for hints :)
|
// Make me compile! Execute `rustlings hint clippy2` for hints :)
|
||||||
|
|
||||||
// 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);
|
||||||
|
|||||||
@ -2,17 +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()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -33,10 +33,18 @@ 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 {
|
||||||
|
let (name, age) = s.split_once(",").unwrap_or_default();
|
||||||
|
if let Ok(age) = age.parse::<usize>() {
|
||||||
|
if name.len() > 0 {
|
||||||
|
return Person {
|
||||||
|
name: String::from(name),
|
||||||
|
age,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Default::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -26,8 +26,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
|
||||||
@ -41,6 +39,20 @@ 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 data: Vec<&str> = s.split(",").collect();
|
||||||
|
if data.len() != 2 {
|
||||||
|
return Err(ParsePersonError::BadLen);
|
||||||
|
}
|
||||||
|
let name: String = data[0].into();
|
||||||
|
if name.is_empty() {
|
||||||
|
return Err(ParsePersonError::NoName);
|
||||||
|
}
|
||||||
|
let age = data[1];
|
||||||
|
let age = age.parse::<usize>().map_err(ParsePersonError::ParseInt)?;
|
||||||
|
Ok(Person { name, age })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -21,8 +21,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,
|
||||||
@ -36,6 +34,12 @@ 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, g, b) = tuple;
|
||||||
|
Ok(Color {
|
||||||
|
red: u8::try_from(r).map_err(|_| IntoColorError::IntConversion)?,
|
||||||
|
green: u8::try_from(g).map_err(|_| IntoColorError::IntConversion)?,
|
||||||
|
blue: u8::try_from(b).map_err(|_| IntoColorError::IntConversion)?,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -43,6 +47,11 @@ 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> {
|
||||||
|
Ok(Color {
|
||||||
|
red: u8::try_from(arr[0]).map_err(|_| IntoColorError::IntConversion)?,
|
||||||
|
green: u8::try_from(arr[1]).map_err(|_| IntoColorError::IntConversion)?,
|
||||||
|
blue: u8::try_from(arr[2]).map_err(|_| IntoColorError::IntConversion)?,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,6 +59,11 @@ 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);
|
||||||
|
}
|
||||||
|
let array = <[i16; 3]>::try_from(slice).unwrap();
|
||||||
|
Color::try_from(array)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -5,11 +5,9 @@
|
|||||||
// 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
|
||||||
// and returns the proper type.
|
// and returns the proper type.
|
||||||
|
|
||||||
// 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() {
|
||||||
|
|||||||
@ -1,8 +1,6 @@
|
|||||||
// macros1.rs
|
// macros1.rs
|
||||||
// Make me compile! Execute `rustlings hint macros1` for hints :)
|
// Make me compile! Execute `rustlings hint macros1` for hints :)
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
macro_rules! my_macro {
|
macro_rules! my_macro {
|
||||||
() => {
|
() => {
|
||||||
println!("Check out my macro!");
|
println!("Check out my macro!");
|
||||||
@ -10,5 +8,5 @@ macro_rules! my_macro {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
my_macro();
|
my_macro!();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,14 +1,12 @@
|
|||||||
// macros2.rs
|
// macros2.rs
|
||||||
// Make me compile! Execute `rustlings hint macros2` for hints :)
|
// Make me compile! Execute `rustlings hint macros2` for hints :)
|
||||||
|
|
||||||
// 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!();
|
||||||
|
}
|
||||||
|
|||||||
@ -2,9 +2,8 @@
|
|||||||
// 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` for hints :)
|
// Execute `rustlings hint macros3` for hints :)
|
||||||
|
|
||||||
// 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!");
|
||||||
|
|||||||
@ -1,15 +1,13 @@
|
|||||||
// macros4.rs
|
// macros4.rs
|
||||||
// Make me compile! Execute `rustlings hint macros4` for hints :)
|
// Make me compile! Execute `rustlings hint macros4` for hints :)
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
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() {
|
||||||
|
|||||||
@ -5,7 +5,11 @@
|
|||||||
|
|
||||||
// Write a macro that passes the quiz! No hints this time, you can do it!
|
// Write a macro that passes the quiz! No hints this time, you can do it!
|
||||||
|
|
||||||
// I AM NOT DONE
|
macro_rules! my_macro {
|
||||||
|
($val:expr) => {
|
||||||
|
format!("Hello {}", $val)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
|||||||
@ -6,8 +6,6 @@
|
|||||||
// list_of_results functions.
|
// list_of_results functions.
|
||||||
// Execute `rustlings hint iterators3` to get some hints!
|
// Execute `rustlings hint iterators3` to get some hints!
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub enum DivisionError {
|
pub enum DivisionError {
|
||||||
NotDivisible(NotDivisibleError),
|
NotDivisible(NotDivisibleError),
|
||||||
@ -39,14 +37,14 @@ pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
|
|||||||
// Desired output: Ok([1, 11, 1426, 3])
|
// Desired output: Ok([1, 11, 1426, 3])
|
||||||
fn result_with_list() -> Result<Vec<i32>, DivisionError> {
|
fn result_with_list() -> Result<Vec<i32>, DivisionError> {
|
||||||
let numbers = vec![27, 297, 38502, 81];
|
let numbers = vec![27, 297, 38502, 81];
|
||||||
numbers.into_iter().map(|n| divide(n, 27)).collect();
|
numbers.into_iter().map(|n| divide(n, 27)).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Complete the function and return a value of the correct type so the test passes.
|
// Complete the function and return a value of the correct type so the test passes.
|
||||||
// Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)]
|
// Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)]
|
||||||
fn list_of_results() -> () {
|
fn list_of_results() -> Vec<Result<i32, DivisionError>> {
|
||||||
let numbers = vec![27, 297, 38502, 81];
|
let numbers = vec![27, 297, 38502, 81];
|
||||||
let division_results = numbers.into_iter().map(|n| divide(n, 27));
|
numbers.into_iter().map(|n| divide(n, 27)).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@ -1,17 +1,7 @@
|
|||||||
// iterators4.rs
|
// iterators4.rs
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
pub fn factorial(num: u64) -> u64 {
|
pub fn factorial(num: u64) -> u64 {
|
||||||
// Complete this function to return the factorial of num
|
(1..=num).into_iter().fold(1, |acc, x| acc * x)
|
||||||
// Do not use:
|
|
||||||
// - return
|
|
||||||
// Try not to use:
|
|
||||||
// - imperative style loops (for, while)
|
|
||||||
// - additional variables
|
|
||||||
// For an extra challenge, don't use:
|
|
||||||
// - recursion
|
|
||||||
// Execute `rustlings hint iterators4` for hints.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@ -10,8 +10,6 @@
|
|||||||
//
|
//
|
||||||
// Make the code compile and the tests pass.
|
// Make the code compile and the tests pass.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
@ -34,6 +32,7 @@ fn count_for(map: &HashMap<String, Progress>, value: Progress) -> usize {
|
|||||||
fn count_iterator(map: &HashMap<String, Progress>, value: Progress) -> usize {
|
fn count_iterator(map: &HashMap<String, Progress>, value: Progress) -> usize {
|
||||||
// map is a hashmap with String keys and Progress values.
|
// map is a hashmap with String keys and Progress values.
|
||||||
// map = { "variables1": Complete, "from_str": None, ... }
|
// map = { "variables1": Complete, "from_str": None, ... }
|
||||||
|
map.into_iter().filter(|&(k, v)| v == &value).count()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
|
fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
|
||||||
@ -52,6 +51,9 @@ fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Pr
|
|||||||
// collection is a slice of hashmaps.
|
// collection is a slice of hashmaps.
|
||||||
// collection = [{ "variables1": Complete, "from_str": None, ... },
|
// collection = [{ "variables1": Complete, "from_str": None, ... },
|
||||||
// { "variables2": Complete, ... }, ... ]
|
// { "variables2": Complete, ... }, ... ]
|
||||||
|
collection
|
||||||
|
.into_iter()
|
||||||
|
.fold(0, |acc, x| acc + count_iterator(x, value))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@ -6,9 +6,7 @@
|
|||||||
// 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, Mutex};
|
||||||
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@ -17,15 +15,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 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;
|
let mut status = status_shared.lock().unwrap();
|
||||||
|
status.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));
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user