Finished Rustlings Exercises

This commit is contained in:
tropxy 2020-12-06 16:32:06 +01:00
parent 964b2a331d
commit 16329982f3
74 changed files with 373 additions and 334 deletions

View file

@ -6,12 +6,10 @@
// check clippy's suggestions from the output to solve the exercise.
// Execute `rustlings hint clippy1` for hints :)
// I AM NOT DONE
fn main() {
let x = 1.2331f64;
let y = 1.2332f64;
if y != x {
let x: f64 = 1.2331;
let y: f64 = 1.2332;
if (y - x).abs() > f64::EPSILON {
println!("Success!");
}
}

View file

@ -1,12 +1,10 @@
// clippy2.rs
// Make me compile! Execute `rustlings hint clippy2` for hints :)
// I AM NOT DONE
fn main() {
let mut res = 42;
let option = Some(12);
for x in option {
if let Some(x) = option {
res += x;
}
println!("{}", res);

View file

@ -11,17 +11,15 @@
// Execute the command `rustlings hint collections3` if you need
// hints.
// I AM NOT DONE
use std::collections::HashMap;
fn fruit_basket() -> HashMap<String, u32> {
let mut basket = // TODO: declare your hash map here.
let mut basket = HashMap::new();
// Two bananas are already given for you :)
basket.insert(String::from("banana"), 2);
// TODO: Put more fruits in your basket here.
basket.insert(String::from("apple"), 2);
basket.insert(String::from("mango"), 3);
basket
}
@ -33,14 +31,13 @@ mod tests {
#[test]
fn at_least_three_types_of_fruits() {
let basket = fruit_basket();
println!("{:?}", basket);
assert!(basket.len() >= 3);
}
#[test]
fn at_least_five_fruits() {
let basket = fruit_basket();
assert!(basket
.values()
.sum::<u32>() >= 5);
assert!(basket.values().sum::<u32>() >= 5);
}
}

View file

@ -12,8 +12,6 @@
// Execute the command `rustlings hint collections4` if you need
// hints.
// I AM NOT DONE
use std::collections::HashMap;
#[derive(Hash, PartialEq, Eq)]
@ -38,6 +36,9 @@ fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
// TODO: Put new fruits if not already present. Note that you
// are not allowed to put any type of fruit that's already
// present!
if !basket.contains_key(&fruit) {
basket.insert(fruit, 3);
}
}
}
@ -75,9 +76,7 @@ mod tests {
fn greater_than_eleven_fruits() {
let mut basket = get_fruit_basket();
fruit_basket(&mut basket);
let count = basket
.values()
.sum::<u32>();
let count = basket.values().sum::<u32>();
assert!(count > 11);
}
}

View file

@ -4,11 +4,9 @@
// Make me compile and pass the test!
// Execute the command `rustlings hint collections1` if you need hints.
// I AM NOT DONE
fn array_and_vec() -> ([i32; 4], Vec<i32>) {
let a = [10, 20, 30, 40]; // a plain array
let v = // TODO: declare your vector here with the macro for vectors
let v = a.to_vec();
(a, v)
}

View file

@ -7,14 +7,14 @@
// Execute the command `rustlings hint collections2` if you need
// hints.
// I AM NOT DONE
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for i in v.iter_mut() {
// TODO: Fill this up so that each element in the Vec `v` is
// multiplied by 2.
*i *= 2;
}
// OR
//v.iter_mut().for_each(|x| *x *= 2);
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
v
}
@ -28,11 +28,6 @@ mod tests {
let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect();
let ans = vec_loop(v.clone());
assert_eq!(
ans,
v.iter()
.map(|x| x * 2)
.collect::<Vec<i32>>()
);
assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>());
}
}

View file

@ -2,17 +2,15 @@
// 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.
// I AM NOT DONE
// Obtain the number of bytes (not characters) in the given argument
// 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()
}
// Obtain the number of characters (not bytes) in the given argument
// 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()
}

View file

@ -33,13 +33,68 @@ impl Default for 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
// I AM NOT DONE
//impl From<&str> for Person {
// fn from(s: &str) -> Person {
// if s.len() == 0 {
// return Person::default();
// }
// let string_vector = s.split(',').collect::<Vec<&str>>();
// println!("{:?}", string_vector);
// if string_vector[0] == "" || string_vector.len() < 2 {
// return Person::default();
// } else {
// match string_vector[1].parse::<usize>() {
// Ok(result) => Person {
// name: string_vector[0].to_string(),
// age: result,
// },
// Err(_) => Person::default(),
// }
// }
// }
//}
impl From<&str> for Person {
fn from(s: &str) -> Person {
// splits just in 2 parts
let parts = s.splitn(2, ',').collect::<Vec<&str>>();
// match all parts
match &parts[..] {
[name, age] if !name.is_empty() => age
.parse()
.map(|age| Person {
name: name.to_string(),
age,
})
.unwrap_or_default(),
_ => Person::default(),
}
}
}
//impl From<&str> for Person {
// fn from(s: &str) -> Person {
// if s.len() == 0 {
// Person::default()
// } else {
// let mut person_itr = s.split(',');
// match person_itr.next().map(|name| {
// (
// if name.is_empty() {
// Err("Missing Name")
// } else {
// Ok(name.to_string())
// },
// person_itr.collect::<String>().parse::<usize>(),
// )
// }) {
// Some((Ok(name), Ok(age))) => Person { name, age },
// _ => Person::default(),
// }
// }
// }
//}
fn main() {
// Use the `from` function
let p1 = Person::from("Mark,20");

View file

@ -10,7 +10,6 @@ struct Person {
age: usize,
}
// I AM NOT DONE
// Steps:
// 1. If the length of the provided string is 0, then return an error
// 2. Split the given string on the commas present in it
@ -23,6 +22,19 @@ struct Person {
impl FromStr for Person {
type Err = String;
fn from_str(s: &str) -> Result<Person, Self::Err> {
let parts = s.splitn(2, ',').collect::<Vec<&str>>();
match &parts[..] {
[name, age] if !name.is_empty() => age
.parse()
.map(|age_as_uint| {
Ok(Person {
name: name.to_string(),
age: age_as_uint,
})
})
.unwrap(),
_ => Err("Shit happens".to_string()),
}
}
}

View file

@ -11,8 +11,6 @@ struct Color {
blue: u8,
}
// I AM NOT DONE
// Your task is to complete this implementation
// and return an Ok result of inner type Color.
// You need create implementation for a tuple of three integer,
@ -25,19 +23,40 @@ struct Color {
// Tuple implementation
impl TryFrom<(i16, i16, i16)> for Color {
type Error = String;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {}
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
let (red, green, blue) = tuple;
match (u8::try_from(red), u8::try_from(green), u8::try_from(blue)) {
(Ok(red), Ok(green), Ok(blue)) => Ok(Color { red, green, blue }),
_ => Err(String::from("Failed to convert")),
}
}
}
// Array implementation
impl TryFrom<[i16; 3]> for Color {
type Error = String;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {}
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
let [red, green, blue] = arr;
match (u8::try_from(red), u8::try_from(green), u8::try_from(blue)) {
(Ok(red), Ok(green), Ok(blue)) => Ok(Color { red, green, blue }),
_ => Err(String::from("Failed to convert")),
}
}
}
// Slice implementation
impl TryFrom<&[i16]> for Color {
type Error = String;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {}
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
if slice.len() != 3 {
return Err("The slice has more than 3 items".to_string());
}
let [red, green, blue]: [i16; 3] = slice.try_into().unwrap();
match (u8::try_from(red), u8::try_from(green), u8::try_from(blue)) {
(Ok(red), Ok(green), Ok(blue)) => Ok(Color { red, green, blue }),
_ => Err(String::from("Failed to convert")),
}
}
}
fn main() {
@ -88,17 +107,17 @@ mod tests {
}
#[test]
fn test_array_out_of_range_positive() {
let c: Color = [1000, 10000, 256].try_into();
let c: Result<Color, String> = [1000, 10000, 256].try_into();
assert!(c.is_err());
}
#[test]
fn test_array_out_of_range_negative() {
let c: Color = [-10, -256, -1].try_into();
let c: Result<Color, String> = [-10, -256, -1].try_into();
assert!(c.is_err());
}
#[test]
fn test_array_sum() {
let c: Color = [-1, 255, 255].try_into();
let c: Result<Color, String> = [-1, 255, 255].try_into();
assert!(c.is_err());
}
#[test]

View file

@ -5,11 +5,9 @@
// The goal is to make sure that the division does not fail to compile
// and returns the proper type.
// I AM NOT DONE
fn average(values: &[f64]) -> f64 {
let total = values.iter().fold(0.0, |a, b| a + b);
total / values.len()
total / values.len() as f64
}
fn main() {

View file

@ -1,11 +1,12 @@
// enums1.rs
// Make me compile! Execute `rustlings hint enums1` for hints!
// I AM NOT DONE
#[derive(Debug)]
enum Message {
// TODO: define a few types of messages as used below
Quit,
Echo,
Move,
ChangeColor, // TODO: define a few types of messages as used below
}
fn main() {

View file

@ -1,11 +1,12 @@
// enums2.rs
// Make me compile! Execute `rustlings hint enums2` for hints!
// I AM NOT DONE
#[derive(Debug)]
enum Message {
// TODO: define the different variants used below
Move { x: i32, y: i32 },
Echo(String),
ChangeColor(u8, u8, u8),
Quit, // TODO: define the different variants used below
}
impl Message {

View file

@ -1,10 +1,11 @@
// enums3.rs
// Address all the TODOs to make the tests pass!
// I AM NOT DONE
enum Message {
// TODO: implement the message variant types based on their usage below
ChangeColor((u8, u8, u8)),
Echo(String),
Move(Point),
Quit, // TODO: implement the message variant types based on their usage below
}
struct Point {
@ -36,6 +37,12 @@ impl State {
}
fn process(&mut self, message: Message) {
match message {
Message::ChangeColor(color) => self.change_color(color),
Message::Echo(stringe) => self.echo(stringe),
Message::Move(point) => self.move_position(point),
Message::Quit => self.quit(),
};
// TODO: create a match expression to process the different message variants
}
}

View file

@ -6,14 +6,12 @@
// this function to have.
// Execute `rustlings hint errors1` for hints!
// I AM NOT DONE
pub fn generate_nametag_text(name: String) -> Option<String> {
pub fn generate_nametag_text(name: String) -> Result<String, String> {
if name.len() > 0 {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
} else {
// Empty names aren't allowed.
None
Err("`name` was empty; it must be nonempty.".to_string())
}
}
@ -28,7 +26,7 @@ mod tests {
fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!(
generate_nametag_text("Beyoncé".into()),
Some("Hi! My name is Beyoncé".into())
Ok("Hi! My name is Beyoncé".into())
);
}

View file

@ -16,15 +16,16 @@
// There are at least two ways to implement this that are both correct-- but
// one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways.
// I AM NOT DONE
use std::num::ParseIntError;
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>();
let qty = item_quantity.parse::<i32>()?;
/* match item_quantity.parse::<i32>() {*/
//Ok(qty) => Ok(qty * cost_per_item + processing_fee),
//Err(e) => Err(e),
/*}*/
Ok(qty * cost_per_item + processing_fee)
}

View file

@ -4,24 +4,8 @@
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints!
// I AM NOT DONE
use std::num::ParseIntError;
fn main() {
let mut tokens = 100;
let pretend_user_input = "8";
let cost = total_cost(pretend_user_input)?;
if cost > tokens {
println!("You can't afford that many!");
} else {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
}
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
@ -29,3 +13,18 @@ pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
Ok(qty * cost_per_item + processing_fee)
}
fn main() -> Result<(), ParseIntError> {
let mut tokens = 100;
let pretend_user_input = "8";
println!("{:?}", total_cost(pretend_user_input));
let cost = total_cost(pretend_user_input)?;
if cost > tokens {
println!("You can't afford that many!");
} else {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
Ok(())
}

View file

@ -17,19 +17,19 @@
//
// Execute `rustlings hint errorsn` for hints :)
// I AM NOT DONE
use std::error;
use std::fmt;
use std::io;
// PositiveNonzeroInteger is a struct defined below the tests.
fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger, ???> {
fn read_and_validate(
b: &mut dyn io::BufRead,
) -> Result<PositiveNonzeroInteger, Box<dyn error::Error>> {
let mut line = String::new();
b.read_line(&mut line);
let num: i64 = line.trim().parse();
let answer = PositiveNonzeroInteger::new(num);
answer
b.read_line(&mut line)?;
let num: i64 = line.trim().parse()?;
let answer = PositiveNonzeroInteger::new(num)?;
Ok(answer)
}
//

View file

@ -1,8 +1,6 @@
// result1.rs
// Make this test pass! Execute `rustlings hint result1` for hints :)
// I AM NOT DONE
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
@ -14,7 +12,17 @@ enum CreationError {
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
Ok(PositiveNonzeroInteger(value as u64))
match value {
value if value < 0 => Err(CreationError::Negative),
0 => Err(CreationError::Zero),
_ => Ok(PositiveNonzeroInteger(value as u64)),
}
/*if value < 0 {*/
//return Err(CreationError::Negative);
//} else if value == 0 {
//return Err(CreationError::Zero);
//}
/*Ok(PositiveNonzeroInteger(value as u64))*/
}
}

View file

@ -1,7 +1,7 @@
// functions1.rs
// Make me compile! Execute `rustlings hint functions1` for hints :)
// I AM NOT DONE
fn call_me() {}
fn main() {
call_me();

View file

@ -1,14 +1,12 @@
// functions2.rs
// Make me compile! Execute `rustlings hint functions2` for hints :)
// I AM NOT DONE
fn main() {
call_me(3);
}
fn call_me(num) {
fn call_me(num: i8) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
fn main() {
call_me(3);
}

View file

@ -1,14 +1,12 @@
// functions3.rs
// Make me compile! Execute `rustlings hint functions3` for hints :)
// I AM NOT DONE
fn main() {
call_me();
call_me(None);
}
fn call_me(num: i32) {
for i in 0..num {
fn call_me(num: Option<i32>) {
for i in 0..num.unwrap_or(0) {
println!("Ring! Call number {}", i + 1);
}
}

View file

@ -4,14 +4,12 @@
// This store is having a sale where if the price is an even number, you get
// 10 Rustbucks off, but if it's an odd number, it's 3 Rustbucks off.
// I AM NOT DONE
fn main() {
let original_price = 51;
println!("Your sale price is {}", sale_price(original_price));
}
fn sale_price(price: i32) -> {
fn sale_price(price: i32) -> i32 {
if is_even(price) {
price - 10
} else {

View file

@ -1,13 +1,11 @@
// functions5.rs
// Make me compile! Execute `rustlings hint functions5` for hints :)
// I AM NOT DONE
fn main() {
let answer = square(3);
println!("The answer is {}", answer);
}
fn square(num: i32) -> i32 {
num * num;
num * num
}

View file

@ -1,9 +1,7 @@
// This shopping list program isn't compiling!
// Use your knowledge of generics to fix it.
// I AM NOT DONE
fn main() {
let mut shopping_list: Vec<?> = Vec::new();
let mut shopping_list: Vec<&str> = Vec::new();
shopping_list.push("milk");
}

View file

@ -1,14 +1,12 @@
// This powerful wrapper provides the ability to store a positive integer value.
// Rewrite it using generics so that it supports wrapping ANY type.
// I AM NOT DONE
struct Wrapper {
value: u32,
struct Wrapper<T> {
value: T,
}
impl Wrapper {
pub fn new(value: u32) -> Self {
impl<T> Wrapper<T> {
pub fn new(value: T) -> Self {
Wrapper { value }
}
}

View file

@ -10,18 +10,18 @@
// Execute 'rustlings hint generics3' for hints!
// I AM NOT DONE
pub struct ReportCard {
pub grade: f32,
pub struct ReportCard<T> {
pub grade: T,
pub student_name: String,
pub student_age: u8,
}
impl ReportCard {
impl<T: std::fmt::Display> ReportCard<T> {
pub fn print(&self) -> String {
format!("{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade)
format!(
"{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade
)
}
}
@ -46,7 +46,7 @@ mod tests {
fn generate_alphabetic_report_card() {
// TODO: Make sure to change the grade here after you finish the exercise.
let report_card = ReportCard {
grade: 2.1,
grade: "A+",
student_name: "Gary Plotter".to_string(),
student_age: 11,
};

View file

@ -1,13 +1,12 @@
// if1.rs
// I AM NOT DONE
pub fn bigger(a: i32, b: i32) -> i32 {
// Complete this function to return the bigger number!
// Do not use:
// - another function call
// - additional variables
// Execute `rustlings hint if1` for hints
return if a >= b { a } else { b };
}
// Don't mind this for now :)

View file

@ -4,13 +4,11 @@
// Step 2: Get the bar_for_fuzz and default_to_baz tests passing!
// Execute the command `rustlings hint if2` if you want a hint :)
// I AM NOT DONE
pub fn fizz_if_foo(fizzish: &str) -> &str {
if fizzish == "fizz" {
"foo"
} else {
1
match fizzish {
"fizz" => "foo",
"fuzz" => "bar",
_ => "baz",
}
}

View file

@ -1,8 +1,6 @@
// macros1.rs
// Make me compile! Execute `rustlings hint macros1` for hints :)
// I AM NOT DONE
macro_rules! my_macro {
() => {
println!("Check out my macro!");
@ -10,5 +8,5 @@ macro_rules! my_macro {
}
fn main() {
my_macro();
my_macro!();
}

View file

@ -1,14 +1,12 @@
// macros2.rs
// Make me compile! Execute `rustlings hint macros2` for hints :)
// I AM NOT DONE
fn main() {
my_macro!();
}
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
fn main() {
my_macro!();
}

View file

@ -2,8 +2,7 @@
// Make me compile, without taking the macro out of the module!
// Execute `rustlings hint macros3` for hints :)
// I AM NOT DONE
#[macro_use]
mod macros {
macro_rules! my_macro {
() => {
@ -11,7 +10,6 @@ mod macros {
};
}
}
fn main() {
my_macro!();
}

View file

@ -1,15 +1,13 @@
// macros4.rs
// Make me compile! Execute `rustlings hint macros4` for hints :)
// I AM NOT DONE
macro_rules! my_macro {
() => {
println!("Check out my macro!");
}
};
($val:expr) => {
println!("Look at this other macro: {}", $val);
}
};
}
fn main() {

View file

@ -1,10 +1,8 @@
// modules1.rs
// Make me compile! Execute `rustlings hint modules1` for hints :)
// I AM NOT DONE
mod sausage_factory {
fn make_sausage() {
pub fn make_sausage() {
println!("sausage!");
}
}

View file

@ -1,11 +1,9 @@
// modules2.rs
// Make me compile! Execute `rustlings hint modules2` for hints :)
// I AM NOT DONE
mod delicious_snacks {
use self::fruits::PEAR as fruit;
use self::veggies::CUCUMBER as veggie;
pub use self::fruits::PEAR as fruit;
pub use self::veggies::CUCUMBER as veggie;
mod fruits {
pub const PEAR: &'static str = "Pear";

View file

@ -1,12 +1,10 @@
// move_semantics1.rs
// Make me compile! Execute `rustlings hint move_semantics1` for hints :)
// I AM NOT DONE
fn main() {
let vec0 = Vec::new();
let vec1 = fill_vec(vec0);
let mut vec1 = fill_vec(vec0);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);

View file

@ -2,23 +2,21 @@
// Make me compile without changing line 13!
// Execute `rustlings hint move_semantics2` for hints :)
// I AM NOT DONE
fn main() {
let vec0 = Vec::new();
let mut vec1 = fill_vec(vec0);
let mut vec1 = fill_vec(&vec0);
// Do not change the following line!
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);
println!("{} has length {} content `{:?}`", "vec-2", vec0.len(), vec0);
vec1.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
fn fill_vec(vec: &Vec<i32>) -> Vec<i32> {
let mut vec = vec.clone();
vec.push(22);
vec.push(44);

View file

@ -3,8 +3,6 @@
// (no lines with multiple semicolons necessary!)
// Execute `rustlings hint move_semantics3` for hints :)
// I AM NOT DONE
fn main() {
let vec0 = Vec::new();
@ -17,7 +15,7 @@ fn main() {
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
vec.push(22);
vec.push(44);
vec.push(66);

View file

@ -4,12 +4,8 @@
// freshly created vector from fill_vec to its caller.
// Execute `rustlings hint move_semantics4` for hints!
// I AM NOT DONE
fn main() {
let vec0 = Vec::new();
let mut vec1 = fill_vec(vec0);
let mut vec1 = fill_vec();
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
@ -20,7 +16,7 @@ fn main() {
// `fill_vec()` no longer take `vec: Vec<i32>` as argument
fn fill_vec() -> Vec<i32> {
let mut vec = vec;
let mut vec = Vec::new();
vec.push(22);
vec.push(44);

View file

@ -1,23 +1,20 @@
// option1.rs
// Make me compile! Execute `rustlings hint option1` for hints
// I AM NOT DONE
// you can modify anything EXCEPT for this function's sig
fn print_number(maybe_number: Option<u16>) {
println!("printing: {}", maybe_number.unwrap());
}
fn main() {
print_number(13);
print_number(99);
print_number(Some(13));
print_number(Some(99));
let mut numbers: [Option<u16>; 5];
numbers = [Some(0); 5];
for iter in 0..5 {
let number_to_add: u16 = {
((iter * 1235) + 2) / (4 * 16)
};
let number_to_add: u16 = { ((iter * 1235) + 2) / (4 * 16) };
numbers[iter as usize] = number_to_add;
numbers[iter as usize] = Some(number_to_add);
}
}

View file

@ -1,12 +1,10 @@
// option2.rs
// Make me compile! Execute `rustlings hint option2` for hints
// I AM NOT DONE
fn main() {
let optional_value = Some(String::from("rustlings"));
// TODO: Make this an if let statement whose value is "Some" type
value = optional_value {
if let Some(value) = optional_value {
println!("the value of optional value is: {}", value);
} else {
println!("The optional value doesn't contain anything!");
@ -19,7 +17,9 @@ fn main() {
// TODO: make this a while let statement - remember that vector.pop also adds another layer of Option<T>
// You can stack `Option<T>`'s into while let and if let
value = optional_values_vec.pop() {
println!("current value: {}", value);
while let Some(vector_value) = optional_values_vec.pop() {
if let Some(value) = vector_value {
println!("current value: {}", value);
}
}
}

View file

@ -2,8 +2,6 @@
// Fill in the rest of the line that has code missing!
// No hints, there's no tricks, just get used to typing these :)
// I AM NOT DONE
fn main() {
// Booleans (`bool`)
@ -12,8 +10,7 @@ fn main() {
println!("Good morning!");
}
let // Finish the rest of this line like the example! Or make it be false!
if is_evening {
if !is_morning {
println!("Good evening!");
}
}

View file

@ -2,8 +2,6 @@
// Fill in the rest of the line that has code missing!
// No hints, there's no tricks, just get used to typing these :)
// I AM NOT DONE
fn main() {
// Characters (`char`)
@ -16,9 +14,9 @@ fn main() {
println!("Neither alphabetic nor numeric!");
}
let // Finish this line like the example! What's your favorite character?
// Try a letter, try a number, try a special character, try a character
// from a different language than your own, try an emoji!
let your_character = 'A'; // Finish this line like the example! What's your favorite character?
// Try a letter, try a number, try a special character, try a character
// from a different language than your own, try an emoji!
if your_character.is_alphabetic() {
println!("Alphabetical!");
} else if your_character.is_numeric() {

View file

@ -2,10 +2,10 @@
// Create an array with at least 100 elements in it where the ??? is.
// Execute `rustlings hint primitive_types3` for hints!
// I AM NOT DONE
fn main() {
let a = ???
let mut a = vec![0; 200];
a = (0..100).collect();
println!("{}", a.len());
if a.len() >= 100 {
println!("Wow, that's a big array!");

View file

@ -2,13 +2,11 @@
// Get a slice out of Array a where the ??? is so that the test passes.
// Execute `rustlings hint primitive_types4` for hints!!
// I AM NOT DONE
#[test]
fn slice_out_of_array() {
let a = [1, 2, 3, 4, 5];
let nice_slice = ???
let nice_slice = &a[1..4];
assert_eq!([2, 3, 4], nice_slice)
}

View file

@ -2,11 +2,9 @@
// Destructure the `cat` tuple so that the println will work.
// Execute `rustlings hint primitive_types5` for hints!
// I AM NOT DONE
fn main() {
let cat = ("Furry McFurson", 3.5);
let /* your pattern here */ = cat;
let (name, age) = cat;
println!("{} is {} years old.", name, age);
}

View file

@ -3,14 +3,11 @@
// You can put the expression for the second element where ??? is so that the test passes.
// Execute `rustlings hint primitive_types6` for hints!
// I AM NOT DONE
#[test]
fn indexing_tuple() {
let numbers = (1, 2, 3);
// Replace below ??? with the tuple indexing syntax.
let second = ???;
let second = numbers.1;
assert_eq!(2, second,
"This is not the 2nd number in the tuple!")
assert_eq!(2, second, "This is not the 2nd number in the tuple!")
}

View file

@ -7,11 +7,17 @@
// more than 40 at once, each apple only costs 1! Write a function that calculates
// the price of an order of apples given the order amount. No hints this time!
// I AM NOT DONE
// Put your function here!
// fn ..... {
fn calculate_apple_price(number_apples: i8) -> i8 {
if number_apples >= 40 {
number_apples
} else {
number_apples * 2
}
}
// Don't modify this function!
#[test]
fn verify_test() {

View file

@ -7,8 +7,6 @@
// you think each value is. That is, add either `string_slice` or `string`
// before the parentheses on each line. If you're right, it will compile!
// I AM NOT DONE
fn string_slice(arg: &str) {
println!("{}", arg);
}
@ -17,14 +15,14 @@ fn string(arg: String) {
}
fn main() {
???("blue");
???("red".to_string());
???(String::from("hi"));
???("rust is fun!".to_owned());
???("nice weather".into());
???(format!("Interpolation {}", "Station"));
???(&String::from("abc")[0..1]);
???(" hello there ".trim());
???("Happy Monday!".to_string().replace("Mon", "Tues"));
???("mY sHiFt KeY iS sTiCkY".to_lowercase());
string_slice("blue");
string("red".to_string());
string(String::from("hi"));
string("rust is fun!".to_owned());
string("nice weather".into());
string(format!("Interpolation {}", "Station"));
string_slice(&String::from("abc")[0..1]);
string_slice(" hello there ".trim());
string("Happy Monday!".to_string().replace("Mon", "Tues"));
string("mY sHiFt KeY iS sTiCkY".to_lowercase());
}

View file

@ -7,8 +7,6 @@
// we expect to get when we call `times_two` with a negative number.
// No hints, you can do this :)
// I AM NOT DONE
pub fn times_two(num: i32) -> i32 {
num * 2
}
@ -19,11 +17,12 @@ mod tests {
#[test]
fn returns_twice_of_positive_numbers() {
assert_eq!(times_two(4), ???);
assert_eq!(times_two(4), 8);
}
#[test]
fn returns_twice_of_negative_numbers() {
// TODO write an assert for `times_two(-4)`
assert_eq!(times_two(-4), -8);
}
}

View file

@ -5,7 +5,11 @@
// 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)]
mod tests {

View file

@ -4,18 +4,18 @@
// somewhere. Try not to create any copies of the `numbers` Vec!
// Execute `rustlings hint arc1` for hints :)
// I AM NOT DONE
#![forbid(unused_imports)] // Do not change this, (or the next) line.
use std::sync::Arc;
use std::thread;
fn main() {
let numbers: Vec<_> = (0..100u32).collect();
let shared_numbers = // TODO
let shared_numbers = Arc::new(numbers);
let mut joinhandles = Vec::new();
for offset in 0..8 {
//let child_numbers = Arc::clone(&shared_numbers);
let child_numbers = shared_numbers.clone();
joinhandles.push(thread::spawn(move || {
let mut i = offset;
let mut sum = 0;

View file

@ -16,14 +16,14 @@
//
// Execute `rustlings hint box1` for hints :)
// I AM NOT DONE
#[derive(PartialEq, Debug)]
pub enum List {
Cons(i32, List),
Cons(i32, Box<List>),
Nil,
}
//use crate::List::{Cons, Nil};
fn main() {
println!("This is an empty cons list: {:?}", create_empty_list());
println!(
@ -33,11 +33,11 @@ fn main() {
}
pub fn create_empty_list() -> List {
unimplemented!()
List::Nil
}
pub fn create_non_empty_list() -> List {
unimplemented!()
List::Cons(1, Box::new(List::Cons(1, Box::new(List::Nil))))
}
#[cfg(test)]

View file

@ -1,24 +1,22 @@
// iterators1.rs
//
//
// Make me compile by filling in the `???`s
//
// When performing operations on elements within a collection, iterators are essential.
// This module helps you get familiar with the structure of using an iterator and
// This module helps you get familiar with the structure of using an iterator and
// how to go through elements within an iterable collection.
//
//
// Execute `rustlings hint iterators1` for hints :D
// I AM NOT DONE
fn main () {
fn main() {
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(), ???); // 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(), ???); // TODO: Step 2.1
assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach")); // TODO: Step 2.1
assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry"));
assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3
assert_eq!(my_iterable_fav_fruits.next(), None); // TODO: Step 3
}

View file

@ -7,13 +7,11 @@
// Try to ensure it returns a single string.
// As always, there are hints if you execute `rustlings hint iterators2`!
// I AM NOT DONE
pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars();
match c.next() {
None => String::new(),
Some(first) => first.collect::<String>() + c.as_str(),
Some(first) => first.to_uppercase().collect::<String>() + c.as_str(),
}
}
@ -37,14 +35,20 @@ mod tests {
#[test]
fn test_iterate_string_vec() {
let words = vec!["hello", "world"];
let capitalized_words: Vec<String> = // TODO
let capitalized_words: Vec<String> = words
.into_iter()
.map(|word| capitalize_first(word))
.collect();
assert_eq!(capitalized_words, ["Hello", "World"]);
}
#[test]
fn test_iterate_into_string() {
let words = vec!["hello", " ", "world"];
let capitalized_words = // TODO
let capitalized_words = words
.into_iter()
.map(|word| capitalize_first(word))
.collect::<String>(); //when we specify the type at the end is called a turbofish
assert_eq!(capitalized_words, "Hello World");
}
}

View file

@ -7,8 +7,6 @@
// Execute `rustlings hint iterators3` to get some hints!
// Have fun :-)
// I AM NOT DONE
#[derive(Debug, PartialEq, Eq)]
pub enum DivisionError {
NotDivisible(NotDivisibleError),
@ -24,7 +22,19 @@ pub struct NotDivisibleError {
// This function should calculate `a` divided by `b` if `a` is
// evenly divisible by b.
// Otherwise, it should return a suitable error.
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {}
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
if b == 0 {
return Err(DivisionError::DivideByZero);
}
if a % b == 0 {
return Ok(a / b);
} else {
Err(DivisionError::NotDivisible(NotDivisibleError {
dividend: a,
divisor: b,
}))
}
}
#[cfg(test)]
mod tests {
@ -58,12 +68,11 @@ mod tests {
}
// Iterator exercises using your `divide` function
/*
#[test]
fn result_with_list() {
let numbers = vec![27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));
let x //... Fill in here!
let x = division_results.collect::<Result<Vec<i32>, DivisionError>>();
assert_eq!(format!("{:?}", x), "Ok([1, 11, 1426, 3])");
}
@ -71,8 +80,7 @@ mod tests {
fn list_of_results() {
let numbers = vec![27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));
let x //... Fill in here!
let x = division_results.collect::<Vec<Result<i32, DivisionError>>>();
assert_eq!(format!("{:?}", x), "[Ok(1), Ok(11), Ok(1426), Ok(3)]");
}
*/
}

View file

@ -1,7 +1,5 @@
// iterators4.rs
// I AM NOT DONE
pub fn factorial(num: u64) -> u64 {
// Complete this function to return the factorial of num
// Do not use:
@ -11,7 +9,11 @@ pub fn factorial(num: u64) -> u64 {
// - additional variables
// For an extra challenge, don't use:
// - recursion
// Execute `rustlings hint iterators4` for hints.
// Execute `rustlings hint iterators4` for hints
// Check https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fold
// 4! = 4x3x2x1 = 24
// 5! = 5x4x3x2x1 = 120
(1..=num).fold(1, |acc, x| acc * x)
}
#[cfg(test)]

View file

@ -2,13 +2,11 @@
// Make me compile without changing the function signature!
// Execute `rustlings hint strings1` for hints ;)
// I AM NOT DONE
fn main() {
let answer = current_favorite_color();
println!("My current favorite color is {}", answer);
}
fn current_favorite_color() -> String {
"blue"
"blue".to_string()
}

View file

@ -2,11 +2,9 @@
// Make me compile without changing the function signature!
// Execute `rustlings hint strings2` for hints :)
// I AM NOT DONE
fn main() {
let word = String::from("green"); // Try not changing this line :)
if is_a_color_word(word) {
if is_a_color_word(&word) {
println!("That is a color word I know!");
} else {
println!("That is not a color word I know.");

View file

@ -1,13 +1,12 @@
// structs1.rs
// Address all the TODOs to make the tests pass!
// I AM NOT DONE
struct ColorClassicStruct {
// TODO: Something goes here
name: String,
hex: String,
}
struct ColorTupleStruct(/* TODO: Something goes here */);
struct ColorTupleStruct(String, String);
#[derive(Debug)]
struct UnitStruct;
@ -19,7 +18,10 @@ mod tests {
#[test]
fn classic_c_structs() {
// TODO: Instantiate a classic c struct!
// let green =
let green = ColorClassicStruct {
name: "green".to_string(),
hex: "#00FF00".to_string(),
};
assert_eq!(green.name, "green");
assert_eq!(green.hex, "#00FF00");
@ -28,7 +30,7 @@ mod tests {
#[test]
fn tuple_structs() {
// TODO: Instantiate a tuple struct!
// let green =
let green = ColorTupleStruct("green".to_string(), "#00FF00".to_string());
assert_eq!(green.0, "green");
assert_eq!(green.1, "#00FF00");
@ -37,7 +39,7 @@ mod tests {
#[test]
fn unit_structs() {
// TODO: Instantiate a unit struct!
// let unit_struct =
let unit_struct = UnitStruct;
let message = format!("{:?}s are fun!", unit_struct);
assert_eq!(message, "UnitStructs are fun!");

View file

@ -1,8 +1,6 @@
// structs2.rs
// Address all the TODOs to make the tests pass!
// I AM NOT DONE
#[derive(Debug)]
struct Order {
name: String,
@ -34,7 +32,12 @@ mod tests {
fn your_order() {
let order_template = create_order_template();
// TODO: Create your own order using the update syntax and template above!
// let your_order =
let your_order = Order {
name: "Hacker in Rust".to_string(),
count: 1,
..order_template
};
assert_eq!(your_order.name, "Hacker in Rust");
assert_eq!(your_order.year, order_template.year);
assert_eq!(your_order.made_by_phone, order_template.made_by_phone);

View file

@ -3,8 +3,6 @@
// exercise we have defined the Package struct and we want to test some logic attached to it,
// make the code compile and the tests pass! If you have issues execute `rustlings hint structs3`
// I AM NOT DONE
#[derive(Debug)]
struct Package {
sender_country: String,
@ -15,7 +13,7 @@ struct Package {
impl Package {
fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package {
if weight_in_grams <= 0 {
// Something goes here...
panic!("The package is weightless!")
} else {
return Package {
sender_country,
@ -25,12 +23,15 @@ impl Package {
}
}
fn is_international(&self) -> ??? {
// Something goes here...
fn is_international(&self) -> bool {
if self.sender_country != self.recipient_country {
return true;
}
false
}
fn get_fees(&self, cents_per_gram: i32) -> ??? {
// Something goes here...
fn get_fees(&self, cents_per_gram: i32) -> i32 {
self.weight_in_grams * cents_per_gram
}
}
@ -62,7 +63,7 @@ mod tests {
let sender_country = String::from("Spain");
let recipient_country = String::from("Spain");
let cents_per_gram = ???;
let cents_per_gram = 3;
let package = Package::new(sender_country, recipient_country, 1500);

View file

@ -6,12 +6,10 @@
// This test has a problem with it -- make the test compile! Make the test
// pass! Make the test fail! Execute `rustlings hint tests1` for hints :)
// I AM NOT DONE
#[cfg(test)]
mod tests {
#[test]
fn you_can_assert() {
assert!();
assert!(true);
}
}

View file

@ -2,12 +2,10 @@
// This test has a problem with it -- make the test compile! Make the test
// pass! Make the test fail! Execute `rustlings hint tests2` for hints :)
// I AM NOT DONE
#[cfg(test)]
mod tests {
#[test]
fn you_can_assert_eq() {
assert_eq!();
assert_eq!(1, 1);
}
}

View file

@ -4,8 +4,6 @@
// we expect to get when we call `is_even(5)`.
// Execute `rustlings hint tests3` for hints :)
// I AM NOT DONE
pub fn is_even(num: i32) -> bool {
num % 2 == 0
}
@ -16,11 +14,11 @@ mod tests {
#[test]
fn is_true_when_even() {
assert!();
assert!(is_even(0));
}
#[test]
fn is_false_when_odd() {
assert!();
assert!(!is_even(5));
}
}

View file

@ -5,26 +5,25 @@
// of "waiting..." and the program ends without timing out when running,
// you've got it :)
// I AM NOT DONE
use std::sync::Arc;
use std::sync::RwLock;
use std::thread;
use std::time::Duration;
struct JobStatus {
jobs_completed: u32,
}
fn main() {
let status = Arc::new(JobStatus { jobs_completed: 0 });
let status = Arc::new(RwLock::new(JobStatus { jobs_completed: 0 }));
let status_shared = status.clone();
thread::spawn(move || {
for _ in 0..10 {
thread::sleep(Duration::from_millis(250));
status_shared.jobs_completed += 1;
let mut status_write = status_shared.write().unwrap();
status_write.jobs_completed += 1;
}
});
while status.jobs_completed < 10 {
while status.read().unwrap().jobs_completed < 10 {
println!("waiting... ");
thread::sleep(Duration::from_millis(500));
}

View file

@ -8,19 +8,20 @@
// which appends "Bar" to any object
// implementing this trait.
// I AM NOT DONE
trait AppendBar {
fn append_bar(self) -> Self;
}
impl AppendBar for String {
//Add your code here
fn append_bar(mut self) -> Self {
self.push_str("Bar");
self
}
}
fn main() {
let s = String::from("Foo");
let s = s.append_bar();
let mut s = s.append_bar();
println!("s: {}", s);
}

View file

@ -10,13 +10,16 @@
// No boiler plate code this time,
// you can do this!
// I AM NOT DONE
trait AppendBar {
fn append_bar(self) -> Self;
}
//TODO: Add your code here
impl AppendBar for Vec<String> {
fn append_bar(mut self) -> Self {
self.push("Bar".to_string());
self
}
}
#[cfg(test)]
mod tests {

View file

@ -6,9 +6,7 @@
// even after you already figured it out. If you got everything working and
// feel ready for the next exercise, remove the `I AM NOT DONE` comment below.
// I AM NOT DONE
fn main() {
x = 5;
let x: i8 = 5;
println!("x has the value {}", x);
}

View file

@ -1,10 +1,8 @@
// variables2.rs
// Make me compile! Execute the command `rustlings hint variables2` if you want a hint :)
// I AM NOT DONE
fn main() {
let x;
let x: i8 = 0;
if x == 10 {
println!("Ten!");
} else {

View file

@ -1,10 +1,8 @@
// variables3.rs
// Make me compile! Execute the command `rustlings hint variables3` if you want a hint :)
// I AM NOT DONE
fn main() {
let x = 3;
let mut x = 3;
println!("Number {}", x);
x = 5; // don't change this line
println!("Number {}", x);

View file

@ -1,9 +1,7 @@
// variables4.rs
// Make me compile! Execute the command `rustlings hint variables4` if you want a hint :)
// I AM NOT DONE
fn main() {
let x: i32;
let x: i32 = 0;
println!("Number {}", x);
}

View file

@ -1,11 +1,12 @@
// variables5.rs
// Make me compile! Execute the command `rustlings hint variables5` if you want a hint :)
// I AM NOT DONE
fn main() {
let number = "T-H-R-E-E";
let mut number = "T-H-R-E-E";
println!("Spell a Number : {}", number);
number = 3;
println!("Number plus two is : {}", number + 2);
let number = &3.to_string();
println!(
"Number plus two is : {}",
number.parse::<i32>().unwrap() + 2
);
}

View file

@ -1,9 +1,7 @@
// variables6.rs
// Make me compile! Execute the command `rustlings hint variables6` if you want a hint :)
// I AM NOT DONE
const NUMBER = 3;
const NUMBER: i32 = 3;
fn main() {
println!("Number {}", NUMBER);
}