mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-10 04:39:18 +00:00
20231010
This commit is contained in:
parent
d42c582ca3
commit
b9df5b16f2
@ -9,12 +9,12 @@
|
|||||||
// 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,15 @@
|
|||||||
// 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 {
|
/*for x in option {
|
||||||
|
res += x;
|
||||||
|
}*/
|
||||||
|
if let Some(x) = option {
|
||||||
res += x;
|
res += x;
|
||||||
}
|
}
|
||||||
println!("{}", res);
|
println!("{}", res);
|
||||||
|
|||||||
@ -3,28 +3,29 @@
|
|||||||
// 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_none() {
|
||||||
my_option.unwrap();
|
// 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 my_empty_vec = vec![1, 2, 3, 4, 5];
|
||||||
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;
|
//value_a = value_b;
|
||||||
value_b = value_a;
|
//value_b = value_a;
|
||||||
|
std::mem::swap(&mut value_a, &mut value_b);
|
||||||
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
|
|
||||||
|
|
||||||
// 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: 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: AsMut<u32>>(arg: &mut T) {
|
||||||
// TODO: Implement the function body.
|
// TODO: Implement the function body.
|
||||||
???
|
*arg.as_mut() = *arg.as_mut() * *arg.as_mut();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@ -40,10 +40,26 @@ 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 {
|
||||||
|
|
||||||
|
let persion: Vec<&str> = s.split(',').collect();
|
||||||
|
if persion.len() < 2 || persion[0].len() == 0 {
|
||||||
|
return Person::default();
|
||||||
|
}
|
||||||
|
|
||||||
|
let name = persion[0].to_string();
|
||||||
|
let age = match persion[1].parse::<usize>() {
|
||||||
|
Ok(r) => r,
|
||||||
|
_ => return Person::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
Person {
|
||||||
|
name,
|
||||||
|
age
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -31,7 +31,7 @@ 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
|
||||||
@ -52,6 +52,26 @@ 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 persion: Vec<&str> = s.split(',').collect();
|
||||||
|
if persion.len() != 2 {
|
||||||
|
return Err(ParsePersonError::BadLen);
|
||||||
|
}
|
||||||
|
|
||||||
|
if persion[0].len() == 0 {
|
||||||
|
return Err(ParsePersonError::NoName);
|
||||||
|
}
|
||||||
|
|
||||||
|
let name = persion[0].to_string();
|
||||||
|
let age = persion[1].parse::<usize>().map_err(ParsePersonError::ParseInt)?;
|
||||||
|
|
||||||
|
Ok(Person {
|
||||||
|
name,
|
||||||
|
age
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -27,7 +27,7 @@ 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
|
||||||
@ -41,6 +41,16 @@ 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> {
|
||||||
|
if tuple.0 > 255 || tuple.0 < 0 {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
if tuple.1 > 255 || tuple.1 < 0 {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
if tuple.2 > 255 || tuple.2 < 0 {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
Ok(Self { red: tuple.0 as u8, green: tuple.1 as u8, blue: tuple.2 as u8 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -48,6 +58,16 @@ 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[0] > 255 || arr[0] < 0 {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
if arr[1] > 255 || arr[1] < 0 {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
if arr[2] > 255 || arr[2] < 0 {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
Ok(Self { red: arr[0] as u8, green: arr[1] as u8, blue: arr[2] as u8 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,6 +75,19 @@ 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 slice[0] > 255 || slice[0] < 0 {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
if slice[1] > 255 || slice[1] < 0 {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
if slice[2] > 255 || slice[2] < 0 {
|
||||||
|
return Err(IntoColorError::IntConversion);
|
||||||
|
}
|
||||||
|
Ok(Self { red: slice[0] as u8, green: slice[1] as u8, blue: slice[2] as u8 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -10,11 +10,11 @@
|
|||||||
// 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() {
|
||||||
|
|||||||
@ -9,18 +9,18 @@
|
|||||||
// Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn main() {
|
fn main() {
|
||||||
let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"];
|
let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"];
|
||||||
|
|
||||||
let mut my_iterable_fav_fruits = ???; // TODO: Step 1
|
let mut my_iterable_fav_fruits = my_fav_fruits.iter(); // TODO: Step 1
|
||||||
|
|
||||||
assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana"));
|
assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana"));
|
||||||
assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 2
|
assert_eq!(my_iterable_fav_fruits.next(), Some(&"custard apple")); // TODO: Step 2
|
||||||
assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado"));
|
assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado"));
|
||||||
assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3
|
assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach")); // TODO: Step 3
|
||||||
assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry"));
|
assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry"));
|
||||||
assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4
|
assert_eq!(my_iterable_fav_fruits.next(), None); // TODO: Step 4
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,7 +6,7 @@
|
|||||||
// Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
// Step 1.
|
// Step 1.
|
||||||
// Complete the `capitalize_first` function.
|
// Complete the `capitalize_first` function.
|
||||||
@ -15,7 +15,13 @@ pub fn capitalize_first(input: &str) -> String {
|
|||||||
let mut c = input.chars();
|
let mut c = input.chars();
|
||||||
match c.next() {
|
match c.next() {
|
||||||
None => String::new(),
|
None => String::new(),
|
||||||
Some(first) => ???,
|
Some(first) => {
|
||||||
|
let mut s = first.to_uppercase().to_string();
|
||||||
|
while let Some(v) = c.next() {
|
||||||
|
s.push(v);
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -24,7 +30,11 @@ pub fn capitalize_first(input: &str) -> String {
|
|||||||
// Return a vector of strings.
|
// Return a vector of strings.
|
||||||
// ["hello", "world"] -> ["Hello", "World"]
|
// ["hello", "world"] -> ["Hello", "World"]
|
||||||
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
|
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
|
||||||
vec![]
|
let mut out: Vec<String> = vec![];
|
||||||
|
for v in words {
|
||||||
|
out.push(capitalize_first(v));
|
||||||
|
}
|
||||||
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 3.
|
// Step 3.
|
||||||
@ -32,7 +42,11 @@ pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
|
|||||||
// Return a single string.
|
// Return a single string.
|
||||||
// ["hello", " ", "world"] -> "Hello World"
|
// ["hello", " ", "world"] -> "Hello World"
|
||||||
pub fn capitalize_words_string(words: &[&str]) -> String {
|
pub fn capitalize_words_string(words: &[&str]) -> String {
|
||||||
String::new()
|
let mut out = String::new();
|
||||||
|
for v in words {
|
||||||
|
out.push_str(&capitalize_first(v));
|
||||||
|
}
|
||||||
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@ -9,7 +9,7 @@
|
|||||||
// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub enum DivisionError {
|
pub enum DivisionError {
|
||||||
@ -26,23 +26,33 @@ pub struct NotDivisibleError {
|
|||||||
// Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
|
// Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
|
||||||
// Otherwise, return a suitable error.
|
// Otherwise, return a suitable error.
|
||||||
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
|
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
|
||||||
todo!();
|
if b == 0 {
|
||||||
|
return Err(DivisionError::DivideByZero);
|
||||||
|
}
|
||||||
|
|
||||||
|
if a % b == 0 {
|
||||||
|
Ok(a/b)
|
||||||
|
} else {
|
||||||
|
Err(DivisionError::NotDivisible(NotDivisibleError { dividend: a, divisor: b }))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Complete the function and return a value of the correct type so the test
|
// Complete the function and return a value of the correct type so the test
|
||||||
// passes.
|
// passes.
|
||||||
// Desired output: Ok([1, 11, 1426, 3])
|
// Desired output: Ok([1, 11, 1426, 3])
|
||||||
fn result_with_list() -> () {
|
fn result_with_list() -> Result<Vec<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));
|
let division_results = numbers.into_iter().map(|n| divide(n, 27)).flatten().collect::<Vec<_>>();
|
||||||
|
Ok(division_results)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Complete the function and return a value of the correct type so the test
|
// Complete the function and return a value of the correct type so the test
|
||||||
// passes.
|
// 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));
|
let division_results = numbers.into_iter().map(|n| divide(n, 27)).collect::<Vec<_>>();
|
||||||
|
division_results
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// 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
|
// Complete this function to return the factorial of num
|
||||||
@ -15,6 +15,11 @@ pub fn factorial(num: u64) -> u64 {
|
|||||||
// For an extra challenge, don't use:
|
// For an extra challenge, don't use:
|
||||||
// - recursion
|
// - recursion
|
||||||
// Execute `rustlings hint iterators4` for hints.
|
// Execute `rustlings hint iterators4` for hints.
|
||||||
|
match num {
|
||||||
|
0 => 1,
|
||||||
|
1 => 1,
|
||||||
|
_ => factorial(num - 1) * num
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@ -11,7 +11,7 @@
|
|||||||
// Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
@ -35,7 +35,8 @@ 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, ... }
|
||||||
todo!();
|
//todo!();
|
||||||
|
map.iter().filter(|(_, v)| **v == value ).collect::<Vec<_>>().len()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
|
fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
|
||||||
@ -54,7 +55,8 @@ 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, ... }, ... ]
|
||||||
todo!();
|
//todo!();
|
||||||
|
collection.iter().flatten().filter(|(_, v)| **v == value ).collect::<Vec<_>>().len()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
// 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 +12,5 @@ macro_rules! my_macro {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
my_macro();
|
my_macro!();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,12 +3,13 @@
|
|||||||
// 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() {
|
fn main() {
|
||||||
my_macro!();
|
my_macro!();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[macro_export]
|
||||||
macro_rules! my_macro {
|
macro_rules! my_macro {
|
||||||
() => {
|
() => {
|
||||||
println!("Check out my macro!");
|
println!("Check out my macro!");
|
||||||
|
|||||||
@ -5,9 +5,10 @@
|
|||||||
// 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!");
|
||||||
|
|||||||
@ -3,15 +3,15 @@
|
|||||||
// 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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -21,7 +21,7 @@
|
|||||||
//
|
//
|
||||||
// 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;
|
||||||
@ -29,11 +29,11 @@ use std::thread;
|
|||||||
|
|
||||||
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(numbers);
|
||||||
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();
|
||||||
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.iter().filter(|&&n| n % 8 == offset).sum();
|
||||||
println!("Sum of offset {} is {}", offset, sum);
|
println!("Sum of offset {} is {}", offset, sum);
|
||||||
|
|||||||
@ -18,11 +18,11 @@
|
|||||||
//
|
//
|
||||||
// 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,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -35,11 +35,13 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_empty_list() -> List {
|
pub fn create_empty_list() -> List {
|
||||||
todo!()
|
//todo!()
|
||||||
|
List::Nil
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_non_empty_list() -> List {
|
pub fn create_non_empty_list() -> List {
|
||||||
todo!()
|
//todo!()
|
||||||
|
List::Cons(1, Box::new(create_empty_list()))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@ -12,7 +12,7 @@
|
|||||||
//
|
//
|
||||||
// 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;
|
||||||
|
|
||||||
@ -48,7 +48,8 @@ mod tests {
|
|||||||
let slice = [0, 1, 2];
|
let slice = [0, 1, 2];
|
||||||
let mut input = Cow::from(&slice[..]);
|
let mut input = Cow::from(&slice[..]);
|
||||||
match abs_all(&mut input) {
|
match abs_all(&mut input) {
|
||||||
// TODO
|
Cow::Borrowed(_) => Ok(()),
|
||||||
|
_ => Err("Expected owned value"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -60,7 +61,8 @@ mod tests {
|
|||||||
let slice = vec![0, 1, 2];
|
let slice = vec![0, 1, 2];
|
||||||
let mut input = Cow::from(slice);
|
let mut input = Cow::from(slice);
|
||||||
match abs_all(&mut input) {
|
match abs_all(&mut input) {
|
||||||
// TODO
|
Cow::Owned(_) => Ok(()),
|
||||||
|
_ => Err("Expected owned value"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -72,7 +74,8 @@ mod tests {
|
|||||||
let slice = vec![-1, 0, 1];
|
let slice = vec![-1, 0, 1];
|
||||||
let mut input = Cow::from(slice);
|
let mut input = Cow::from(slice);
|
||||||
match abs_all(&mut input) {
|
match abs_all(&mut input) {
|
||||||
// TODO
|
Cow::Owned(_) => Ok(()),
|
||||||
|
_ => Err("Expected owned value"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -10,7 +10,7 @@
|
|||||||
//
|
//
|
||||||
// Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint.
|
// Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
@ -61,17 +61,17 @@ fn main() {
|
|||||||
jupiter.details();
|
jupiter.details();
|
||||||
|
|
||||||
// TODO
|
// TODO
|
||||||
let saturn = Planet::Saturn(Rc::new(Sun {}));
|
let saturn = Planet::Saturn(sun.clone());
|
||||||
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(sun.clone());
|
||||||
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(sun.clone());
|
||||||
println!("reference count = {}", Rc::strong_count(&sun)); // 9 references
|
println!("reference count = {}", Rc::strong_count(&sun)); // 9 references
|
||||||
neptune.details();
|
neptune.details();
|
||||||
|
|
||||||
@ -93,12 +93,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);
|
||||||
|
|||||||
@ -8,7 +8,7 @@
|
|||||||
// 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 +27,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 {
|
||||||
|
|||||||
@ -7,25 +7,26 @@
|
|||||||
// 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::thread;
|
use std::thread;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
use std::sync::RwLock;
|
||||||
|
|
||||||
struct JobStatus {
|
struct JobStatus {
|
||||||
jobs_completed: u32,
|
jobs_completed: RwLock<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let status = Arc::new(JobStatus { jobs_completed: 0 });
|
let status = Arc::new(JobStatus { jobs_completed: RwLock::new(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.jobs_completed.write().unwrap()) += 1;
|
||||||
});
|
});
|
||||||
handles.push(handle);
|
handles.push(handle);
|
||||||
}
|
}
|
||||||
@ -34,6 +35,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.jobs_completed.read().unwrap());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
// 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;
|
||||||
@ -31,6 +31,8 @@ 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 tx2 = tx.clone();
|
||||||
|
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
for val in &qc1.first_half {
|
for val in &qc1.first_half {
|
||||||
println!("sending {:?}", val);
|
println!("sending {:?}", val);
|
||||||
@ -42,7 +44,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