Merge pull request #4 from cgM82589933/day3

day3 (still working but figured it was a good time to merge to main)
This commit is contained in:
Chris Girvin 2022-05-16 20:41:26 -04:00 committed by GitHub
commit 2c55161c79
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 179 additions and 68 deletions

View File

@ -1,11 +1,13 @@
// 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,
}
fn main() {

View File

@ -1,11 +1,13 @@
// 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,
}
impl Message {

View File

@ -1,10 +1,18 @@
// 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
// // solution0
// ChangeColor((u8, u8, u8)),
// Echo(String),
// Move(Point),
// Quit,
// solution1
ChangeColor { color: (u8, u8, u8) },
Echo { s: String },
Move { p: Point },
Quit,
}
struct Point {
@ -37,6 +45,18 @@ impl State {
fn process(&mut self, message: Message) {
// TODO: create a match expression to process the different message variants
match message {
// // solution0
// Message::ChangeColor((r, g, b)) => self.change_color((r, g, b)),
// Message::Echo(s) => self.echo(s),
// Message::Move(p) => self.move_position(p),
// Message::Quit => self.quit(),
// solution1
Message::ChangeColor { color } => self.change_color(color),
Message::Echo { s } => self.echo(s),
Message::Move { p } => self.move_position(p),
Message::Quit => self.quit(),
}
}
}
@ -51,9 +71,21 @@ mod tests {
position: Point { x: 0, y: 0 },
color: (0, 0, 0),
};
state.process(Message::ChangeColor((255, 0, 255)));
state.process(Message::Echo(String::from("hello world")));
state.process(Message::Move(Point { x: 10, y: 15 }));
// // solution0
// state.process(Message::ChangeColor((255, 0, 255)));
// state.process(Message::Echo(String::from("hello world")));
// state.process(Message::Move(Point { x: 10, y: 15 }));
// state.process(Message::Quit);
// solution1
state.process(Message::ChangeColor {
color: (255, 0, 255),
});
state.process(Message::Echo {
s: String::from("hello world"),
});
state.process(Message::Move {
p: Point { x: 10, y: 15 },
});
state.process(Message::Quit);
assert_eq!(state.color, (255, 0, 255));

View File

@ -1,15 +1,13 @@
// modules1.rs
// Make me compile! Execute `rustlings hint modules1` for hints :)
// I AM NOT DONE
mod sausage_factory {
// Don't let anybody outside of this module see this!
fn get_secret_recipe() -> String {
String::from("Ginger")
}
fn make_sausage() {
pub fn make_sausage() {
get_secret_recipe();
println!("sausage!");
}

View File

@ -3,13 +3,11 @@
// 'use' and 'as' keywords. Fix these 'use' statements to make the code compile.
// Make me compile! Execute `rustlings hint modules2` for hints :)
// I AM NOT DONE
mod delicious_snacks {
// TODO: Fix these use statements
use self::fruits::PEAR as ???
use self::veggies::CUCUMBER as ???
pub use self::fruits::PEAR as fruit;
pub use self::veggies::CUCUMBER as veggie;
mod fruits {
pub const PEAR: &'static str = "Pear";

View File

@ -5,10 +5,13 @@
// from the std::time module. Bonus style points if you can do it with one line!
// Make me compile! Execute `rustlings hint modules3` for hints :)
// I AM NOT DONE
// TODO: Complete this use statement
use ???
// solution0
// use std::time::SystemTime;
// use std::time::UNIX_EPOCH;
// solution1
// use unix shell-style glob pattern matching
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
match SystemTime::now().duration_since(UNIX_EPOCH) {

View File

@ -4,12 +4,35 @@
// freshly created vector from fill_vec to its caller.
// Execute `rustlings hint move_semantics4` for hints!
// I AM NOT DONE
// // original code
// fn main() {
// let vec0 = Vec::new();
// let mut vec1 = fill_vec(vec0);
// println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
// vec1.push(88);
// println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
// }
// // original code (cont'd)
// // `fill_vec()` no longer takes `vec: Vec<i32>` as argument
// fn fill_vec() -> Vec<i32> {
// let mut vec = vec;
// vec.push(22);
// vec.push(44);
// vec.push(66);
// vec
// }
// // end of original code
// solution
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);
@ -18,9 +41,11 @@ fn main() {
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
// solution (cont'd)
// `fill_vec()` no longer takes `vec: Vec<i32>` as argument
fn fill_vec() -> Vec<i32> {
let mut vec = vec;
// create mutable vec
let mut vec = Vec::new();
vec.push(22);
vec.push(44);
@ -28,3 +53,4 @@ fn fill_vec() -> Vec<i32> {
vec
}
// end of solution

View File

@ -3,13 +3,23 @@
// adding, changing or removing any of them.
// Execute `rustlings hint move_semantics5` for hints :)
// I AM NOT DONE
// // original code
// fn main() {
// let mut x = 100;
// let y = &mut x;
// let z = &mut x;
// *y += 100;
// *z += 1000;
// assert_eq!(x, 1200);
// }
// // end of orignal code
// solution
fn main() {
let mut x = 100;
let y = &mut x;
let z = &mut x;
*y += 100;
let z = &mut x;
*z += 1000;
assert_eq!(x, 1200);
}

View File

@ -2,24 +2,55 @@
// Make me compile! `rustlings hint move_semantics6` for hints
// You can't change anything except adding or removing references
// I AM NOT DONE
// // original code
// fn main() {
// let data = "Rust is great!".to_string();
// get_char(data);
// string_uppercase(&data);
// }
// // original code (cont'd)
// // Should not take ownership
// fn get_char(data: String) -> char {
// data.chars().last().unwrap()
// }
// // original code (cont'd)
// // Should take ownership
// fn string_uppercase(mut data: &String) {
// data = &data.to_uppercase();
// println!("{}", data);
// }
// // end of original code
// solution
fn main() {
let data = "Rust is great!".to_string();
get_char(data);
// change passed data to ref so as to not take ownership of `data`
get_char(&data);
string_uppercase(&data);
// remove ref so string_uppercase takes ownership of `data`
string_uppercase(data);
}
// solution (cont'd)
// Should not take ownership
fn get_char(data: String) -> char {
// add ref to argument type
fn get_char(data: &String) -> char {
data.chars().last().unwrap()
}
// solution (cont'd)
// Should take ownership
fn string_uppercase(mut data: &String) {
data = &data.to_uppercase();
// remove ref from argument type
fn string_uppercase(mut data: String) {
// remove ref from data
data = data.to_uppercase();
println!("{}", data);
}
// end of solution

View File

@ -2,17 +2,15 @@
// 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`)
let is_morning = true;
let is_morning: bool = true;
if is_morning {
println!("Good morning!");
}
let // Finish the rest of this line like the example! Or make it be false!
let is_evening: bool = true; // Finish the rest of this line like the example! Or make it be false!
if is_evening {
println!("Good evening!");
}

View File

@ -2,12 +2,10 @@
// 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`)
let my_first_initial = 'C';
let my_first_initial: char = 'C';
if my_first_initial.is_alphabetic() {
println!("Alphabetical!");
} else if my_first_initial.is_numeric() {
@ -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: char = '1'; // 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,8 @@
// 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 a = [0; 100];
if a.len() >= 100 {
println!("Wow, that's a big array!");

View File

@ -2,13 +2,25 @@
// 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
// // original code
// #[test]
// fn slice_out_of_array() {
// let a = [1, 2, 3, 4, 5];
// let nice_slice = ???
// assert_eq!([2, 3, 4], nice_slice)
// }
// // end of original code
// solution
#[test]
fn slice_out_of_array() {
let a = [1, 2, 3, 4, 5];
let nice_slice = ???
// create slice from borrowed array `a`
let nice_slice = &a[1..4];
assert_eq!([2, 3, 4], nice_slice)
}
// end of solution

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)/* your pattern here */ = cat;
println!("{} is {} years old.", name, age);
}

View File

@ -3,14 +3,12 @@
// 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 = ???;
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

@ -1,13 +1,13 @@
// 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 /* TODO: Something goes here */);
#[derive(Debug)]
struct UnitStruct;
@ -19,7 +19,10 @@ mod tests {
#[test]
fn classic_c_structs() {
// TODO: Instantiate a classic c struct!
// let green =
let green = ColorClassicStruct {
name: String::from("green"),
hex: String::from("#00FF00"),
};
assert_eq!(green.name, "green");
assert_eq!(green.hex, "#00FF00");
@ -28,7 +31,7 @@ mod tests {
#[test]
fn tuple_structs() {
// TODO: Instantiate a tuple struct!
// let green =
let green = ColorTupleStruct(String::from("green"), String::from("#00FF00"));
assert_eq!(green.0, "green");
assert_eq!(green.1, "#00FF00");
@ -37,7 +40,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: String::from("Hacker in Rust"),
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

@ -4,8 +4,6 @@
// 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,
@ -17,6 +15,7 @@ impl Package {
fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package {
if weight_in_grams <= 0 {
// panic statement goes here...
panic!("Panic!")
} else {
Package {
sender_country,
@ -26,12 +25,14 @@ impl Package {
}
}
fn is_international(&self) -> ??? {
fn is_international(&self) -> bool {
// Something goes here...
self.sender_country.ne(&self.recipient_country)
}
fn get_fees(&self, cents_per_gram: i32) -> ??? {
fn get_fees(&self, cents_per_gram: i32) -> i32 {
// Something goes here...
cents_per_gram * self.weight_in_grams
}
}