mirror of
https://git.aramjonghu.dev/AramJonghu/rustlings.git
synced 2026-10-31 15:36:28 +01:00
Compare commits
1
Commits
main
..
27abea4b5b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27abea4b5b |
Generated
-4
@@ -167,10 +167,6 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "exercises"
|
|
||||||
version = "0.0.0"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fastrand"
|
name = "fastrand"
|
||||||
version = "2.4.1"
|
version = "2.4.1"
|
||||||
|
|||||||
+1
-4
@@ -1,10 +1,7 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
|
||||||
"rustlings-macros",
|
|
||||||
"dev",
|
|
||||||
]
|
|
||||||
exclude = [
|
exclude = [
|
||||||
"tests/test_exercises",
|
"tests/test_exercises",
|
||||||
|
"dev",
|
||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ fn is_even(num: i64) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Fix the function signature.
|
// TODO: Fix the function signature.
|
||||||
fn sale_price(price: i64) -> i64 {
|
fn sale_price(price: i64) -> {
|
||||||
if is_even(price) {
|
if is_even(price) {
|
||||||
price - 10
|
price - 10
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// TODO: Fix the function body without changing the signature.
|
// TODO: Fix the function body without changing the signature.
|
||||||
fn square(num: i32) -> i32 {
|
fn square(num: i32) -> i32 {
|
||||||
num * num
|
num * num;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -4,11 +4,6 @@ fn bigger(a: i32, b: i32) -> i32 {
|
|||||||
// Do not use:
|
// Do not use:
|
||||||
// - another function call
|
// - another function call
|
||||||
// - additional variables
|
// - additional variables
|
||||||
if a > b {
|
|
||||||
a
|
|
||||||
} else {
|
|
||||||
b
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -2,10 +2,8 @@
|
|||||||
fn picky_eater(food: &str) -> &str {
|
fn picky_eater(food: &str) -> &str {
|
||||||
if food == "strawberry" {
|
if food == "strawberry" {
|
||||||
"Yummy!"
|
"Yummy!"
|
||||||
} else if food == "potato" {
|
|
||||||
"I guess I can eat that."
|
|
||||||
} else {
|
} else {
|
||||||
"No thanks!"
|
1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ fn animal_habitat(animal: &str) -> &str {
|
|||||||
let identifier = if animal == "crab" {
|
let identifier = if animal == "crab" {
|
||||||
1
|
1
|
||||||
} else if animal == "gopher" {
|
} else if animal == "gopher" {
|
||||||
2
|
2.0
|
||||||
} else if animal == "snake" {
|
} else if animal == "snake" {
|
||||||
3
|
3
|
||||||
} else {
|
} else {
|
||||||
0
|
"Unknown"
|
||||||
};
|
};
|
||||||
|
|
||||||
// Don't change the expression below!
|
// Don't change the expression below!
|
||||||
|
|||||||
@@ -8,8 +8,7 @@ fn main() {
|
|||||||
|
|
||||||
// TODO: Define a boolean variable with the name `is_evening` before the `if` statement below.
|
// TODO: Define a boolean variable with the name `is_evening` before the `if` statement below.
|
||||||
// The value of the variable should be the negation (opposite) of `is_morning`.
|
// The value of the variable should be the negation (opposite) of `is_morning`.
|
||||||
let is_evening = true;
|
// let …
|
||||||
|
|
||||||
if is_evening {
|
if is_evening {
|
||||||
println!("Good evening!");
|
println!("Good evening!");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ fn main() {
|
|||||||
// Try a letter, try a digit (in single quotes), try a special character, try a character
|
// Try a letter, try a digit (in single quotes), try a special character, try a character
|
||||||
// from a different language than your own, try an emoji 😉
|
// from a different language than your own, try an emoji 😉
|
||||||
// let your_character = '';
|
// let your_character = '';
|
||||||
let your_character = '僕';
|
|
||||||
|
|
||||||
if your_character.is_alphabetic() {
|
if your_character.is_alphabetic() {
|
||||||
println!("Alphabetical!");
|
println!("Alphabetical!");
|
||||||
|
|||||||
@@ -2,14 +2,6 @@ fn main() {
|
|||||||
// TODO: Create an array called `a` with at least 100 elements in it.
|
// TODO: Create an array called `a` with at least 100 elements in it.
|
||||||
// let a = ???
|
// let a = ???
|
||||||
|
|
||||||
let a = [
|
|
||||||
1, 2, 3, 4, 5, 6, 7, 1, 231, 234, 11, 4512, 51, 5, 12, 51, 25, 12, 45, 134, 12, 412, 45,
|
|
||||||
12, 512, 512, 5, 12, 512, 4, 124, 12, 5, 125, 123, 3412, 45, 123, 5123, 5, 12345, 123, 412,
|
|
||||||
56, 1236, 234, 6345, 6534, 6, 547, 456, 754, 6, 345, 34, 534, 6, 235, 123, 4523, 4523, 5,
|
|
||||||
235, 235, 2, 532, 523, 23, 124, 21, 2, 3, 51235, 664, 3466, 345,312,312,421,412,45,1245,123,423,523,56,234,5234,5234,5,346,345,6745,7456,7456,7,456,7456,7,4, 2, 6, 23, 12, 4512, 512,
|
|
||||||
5, 512, 5, 125, 125, 125, 12, 56, 75, 7456, 87,
|
|
||||||
];
|
|
||||||
|
|
||||||
if a.len() >= 100 {
|
if a.len() >= 100 {
|
||||||
println!("Wow, that's a big array!");
|
println!("Wow, that's a big array!");
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ mod tests {
|
|||||||
// TODO: Get a slice called `nice_slice` out of the array `a` so that the test passes.
|
// TODO: Get a slice called `nice_slice` out of the array `a` so that the test passes.
|
||||||
// let nice_slice = ???
|
// let nice_slice = ???
|
||||||
|
|
||||||
let nice_slice = &a[1..4];
|
|
||||||
assert_eq!([2, 3, 4], nice_slice);
|
assert_eq!([2, 3, 4], nice_slice);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,5 @@ fn main() {
|
|||||||
// TODO: Destructure the `cat` tuple in one statement so that the println works.
|
// TODO: Destructure the `cat` tuple in one statement so that the println works.
|
||||||
// let /* your pattern here */ = cat;
|
// let /* your pattern here */ = cat;
|
||||||
|
|
||||||
let (name, age) = cat;
|
|
||||||
|
|
||||||
println!("{name} is {age} years old");
|
println!("{name} is {age} years old");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ fn main() {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn indexing_tuple() {
|
fn indexing_tuple() {
|
||||||
let numbers = (1, 2, 3);
|
let numbers = (1, 2, 3);
|
||||||
@@ -12,7 +11,6 @@ mod tests {
|
|||||||
// TODO: Use a tuple index to access the second element of `numbers`
|
// TODO: Use a tuple index to access the second element of `numbers`
|
||||||
// and assign it to a variable called `second`.
|
// and assign it to a variable called `second`.
|
||||||
// let second = ???;
|
// let second = ???;
|
||||||
let second = numbers.1;
|
|
||||||
|
|
||||||
assert_eq!(second, 2, "This is not the 2nd number in the tuple!");
|
assert_eq!(second, 2, "This is not the 2nd number in the tuple!");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
fn elems_to_vec(a: i32, b: i32, c: i32) -> Vec<i32> {
|
fn elems_to_vec(a: i32, b: i32, c: i32) -> Vec<i32> {
|
||||||
// TODO: Return a vector containing the elements a, b and c (in this order).
|
// TODO: Return a vector containing the elements a, b and c (in this order).
|
||||||
// Use the "vec!" macro.
|
// Use the "vec!" macro.
|
||||||
let vector: Vec<i32> = vec![a, b, c];
|
|
||||||
vector
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ fn vec_loop(input: &[i32]) -> Vec<i32> {
|
|||||||
for element in input {
|
for element in input {
|
||||||
// TODO: Multiply each element in the `input` slice by 2 and push it to
|
// TODO: Multiply each element in the `input` slice by 2 and push it to
|
||||||
// the `output` vector.
|
// the `output` vector.
|
||||||
|
|
||||||
output.push(element * 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
output
|
output
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// TODO: Fix the compiler error in this function.
|
// TODO: Fix the compiler error in this function.
|
||||||
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
|
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
|
||||||
let mut vec = vec;
|
let vec = vec;
|
||||||
|
|
||||||
vec.push(88);
|
vec.push(88);
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ mod tests {
|
|||||||
fn move_semantics2() {
|
fn move_semantics2() {
|
||||||
let vec0 = vec![22, 44, 66];
|
let vec0 = vec![22, 44, 66];
|
||||||
|
|
||||||
let vec1 = fill_vec(vec0.clone());
|
let vec1 = fill_vec(vec0);
|
||||||
|
|
||||||
assert_eq!(vec0, [22, 44, 66]);
|
assert_eq!(vec0, [22, 44, 66]);
|
||||||
assert_eq!(vec1, [22, 44, 66, 88]);
|
assert_eq!(vec1, [22, 44, 66, 88]);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// TODO: Fix the compiler error in the function without adding any new line.
|
// TODO: Fix the compiler error in the function without adding any new line.
|
||||||
fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
|
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
|
||||||
vec.push(88);
|
vec.push(88);
|
||||||
|
|
||||||
vec
|
vec
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ mod tests {
|
|||||||
fn move_semantics4() {
|
fn move_semantics4() {
|
||||||
let mut x = Vec::new();
|
let mut x = Vec::new();
|
||||||
let y = &mut x;
|
let y = &mut x;
|
||||||
y.push(42);
|
|
||||||
let z = &mut x;
|
let z = &mut x;
|
||||||
|
y.push(42);
|
||||||
z.push(13);
|
z.push(13);
|
||||||
assert_eq!(x, [42, 13]);
|
assert_eq!(x, [42, 13]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,12 +4,12 @@
|
|||||||
// removing references (the character `&`).
|
// removing references (the character `&`).
|
||||||
|
|
||||||
// Shouldn't take ownership
|
// Shouldn't take ownership
|
||||||
fn get_char(data: &String) -> char {
|
fn get_char(data: String) -> char {
|
||||||
data.chars().last().unwrap()
|
data.chars().last().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Should take ownership
|
// Should take ownership
|
||||||
fn string_uppercase(mut data: String) {
|
fn string_uppercase(mut data: &String) {
|
||||||
data = data.to_uppercase();
|
data = data.to_uppercase();
|
||||||
|
|
||||||
println!("{data}");
|
println!("{data}");
|
||||||
@@ -18,7 +18,7 @@ fn string_uppercase(mut data: String) {
|
|||||||
fn main() {
|
fn main() {
|
||||||
let data = "Rust is great!".to_string();
|
let data = "Rust is great!".to_string();
|
||||||
|
|
||||||
get_char(&data);
|
get_char(data);
|
||||||
|
|
||||||
string_uppercase(data);
|
string_uppercase(&data);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,9 @@
|
|||||||
struct ColorRegularStruct {
|
struct ColorRegularStruct {
|
||||||
// TODO: Add the fields that the test `regular_structs` expects.
|
// TODO: Add the fields that the test `regular_structs` expects.
|
||||||
// What types should the fields have? What are the minimum and maximum values for RGB colors?
|
// What types should the fields have? What are the minimum and maximum values for RGB colors?
|
||||||
red: u8,
|
|
||||||
green: u8,
|
|
||||||
blue: u8,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ColorTupleStruct(u8, u8, u8);
|
struct ColorTupleStruct(/* TODO: Add the fields that the test `tuple_structs` expects */);
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct UnitStruct;
|
struct UnitStruct;
|
||||||
@@ -23,11 +20,7 @@ mod tests {
|
|||||||
fn regular_structs() {
|
fn regular_structs() {
|
||||||
// TODO: Instantiate a regular struct.
|
// TODO: Instantiate a regular struct.
|
||||||
// let green =
|
// let green =
|
||||||
let green = ColorRegularStruct {
|
|
||||||
red: 0,
|
|
||||||
green: 255,
|
|
||||||
blue: 0,
|
|
||||||
};
|
|
||||||
assert_eq!(green.red, 0);
|
assert_eq!(green.red, 0);
|
||||||
assert_eq!(green.green, 255);
|
assert_eq!(green.green, 255);
|
||||||
assert_eq!(green.blue, 0);
|
assert_eq!(green.blue, 0);
|
||||||
@@ -37,7 +30,7 @@ mod tests {
|
|||||||
fn tuple_structs() {
|
fn tuple_structs() {
|
||||||
// TODO: Instantiate a tuple struct.
|
// TODO: Instantiate a tuple struct.
|
||||||
// let green =
|
// let green =
|
||||||
let green = ColorTupleStruct(0, 255, 0);
|
|
||||||
assert_eq!(green.0, 0);
|
assert_eq!(green.0, 0);
|
||||||
assert_eq!(green.1, 255);
|
assert_eq!(green.1, 255);
|
||||||
assert_eq!(green.2, 0);
|
assert_eq!(green.2, 0);
|
||||||
@@ -46,7 +39,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn unit_structs() {
|
fn unit_structs() {
|
||||||
// TODO: Instantiate a unit struct.
|
// TODO: Instantiate a unit struct.
|
||||||
let unit_struct = UnitStruct;
|
// let unit_struct =
|
||||||
let message = format!("{unit_struct:?}s are fun!");
|
let message = format!("{unit_struct:?}s are fun!");
|
||||||
|
|
||||||
assert_eq!(message, "UnitStructs are fun!");
|
assert_eq!(message, "UnitStructs are fun!");
|
||||||
|
|||||||
@@ -36,12 +36,6 @@ mod tests {
|
|||||||
// TODO: Create your own order using the update syntax and template above!
|
// TODO: Create your own order using the update syntax and template above!
|
||||||
// let your_order =
|
// 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.name, "Hacker in Rust");
|
||||||
assert_eq!(your_order.year, order_template.year);
|
assert_eq!(your_order.year, order_template.year);
|
||||||
assert_eq!(your_order.made_by_phone, order_template.made_by_phone);
|
assert_eq!(your_order.made_by_phone, order_template.made_by_phone);
|
||||||
|
|||||||
@@ -10,18 +10,19 @@ struct Fireworks {
|
|||||||
rockets: usize,
|
rockets: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Fireworks {
|
// TODO: Turn this function into an associated function on `Fireworks`.
|
||||||
fn new() -> Self {
|
fn new_fireworks() -> Fireworks {
|
||||||
Self { rockets: 0 }
|
Fireworks { rockets: 0 }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_rockets(&mut self, rockets: usize) {
|
// TODO: Turn this function into a method on `Fireworks`.
|
||||||
self.rockets += rockets
|
fn add_rockets(fireworks: &mut Fireworks, rockets: usize) {
|
||||||
}
|
fireworks.rockets += rockets
|
||||||
|
}
|
||||||
|
|
||||||
fn start(self) -> String {
|
// TODO: Turn this function into a method on `Fireworks`.
|
||||||
"🚀".repeat(self.rockets)
|
fn start(fireworks: Fireworks) -> String {
|
||||||
}
|
"🚀".repeat(fireworks.rockets)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -1,11 +1,6 @@
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
enum Message {
|
enum Message {
|
||||||
// TODO: Define a few types of messages as used below.
|
// TODO: Define a few types of messages as used below.
|
||||||
Resize,
|
|
||||||
Move,
|
|
||||||
Echo,
|
|
||||||
ChangeColor,
|
|
||||||
Quit,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -7,11 +7,6 @@ struct Point {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
enum Message {
|
enum Message {
|
||||||
// TODO: Define the different variants used below.
|
// TODO: Define the different variants used below.
|
||||||
Resize { width: u64, height: u64 },
|
|
||||||
Move(Point),
|
|
||||||
Echo(String),
|
|
||||||
ChangeColor(u64, u64, u64),
|
|
||||||
Quit,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Message {
|
impl Message {
|
||||||
|
|||||||
@@ -46,13 +46,6 @@ impl State {
|
|||||||
fn process(&mut self, message: Message) {
|
fn process(&mut self, message: Message) {
|
||||||
// TODO: Create a match expression to process the different message
|
// TODO: Create a match expression to process the different message
|
||||||
// variants using the methods defined above.
|
// variants using the methods defined above.
|
||||||
match message {
|
|
||||||
Message::Resize { width, height } => self.resize(width, height),
|
|
||||||
Message::Move(point) => self.move_position(point),
|
|
||||||
Message::Echo(s) => self.echo(s),
|
|
||||||
Message::ChangeColor(red, green, blue) => self.change_color(red, green, blue),
|
|
||||||
Message::Quit => self.quit(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// TODO: Fix the compiler error without changing the function signature.
|
// TODO: Fix the compiler error without changing the function signature.
|
||||||
fn current_favorite_color() -> String {
|
fn current_favorite_color() -> String {
|
||||||
"blue".to_string()
|
"blue"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ fn is_a_color_word(attempt: &str) -> bool {
|
|||||||
fn main() {
|
fn main() {
|
||||||
let word = String::from("green"); // Don't change this line.
|
let word = String::from("green"); // Don't change this line.
|
||||||
|
|
||||||
if is_a_color_word(&word) {
|
if is_a_color_word(word) {
|
||||||
println!("That is a color word I know!");
|
println!("That is a color word I know!");
|
||||||
} else {
|
} else {
|
||||||
println!("That is not a color word I know.");
|
println!("That is not a color word I know.");
|
||||||
|
|||||||
@@ -1,18 +1,13 @@
|
|||||||
fn trim_me(input: &str) -> &str {
|
fn trim_me(input: &str) -> &str {
|
||||||
// TODO: Remove whitespace from both ends of a string.
|
// TODO: Remove whitespace from both ends of a string.
|
||||||
input.trim()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn compose_me(input: &str) -> String {
|
fn compose_me(input: &str) -> String {
|
||||||
// TODO: Add " world!" to the string! There are multiple ways to do this.
|
// TODO: Add " world!" to the string! There are multiple ways to do this.
|
||||||
let world = " world!";
|
|
||||||
let s: String = input.to_owned() + world;
|
|
||||||
s
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn replace_me(input: &str) -> String {
|
fn replace_me(input: &str) -> String {
|
||||||
// TODO: Replace "cars" in the string with "balloons".
|
// TODO: Replace "cars" in the string with "balloons".
|
||||||
input.replace("cars", "balloons")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -13,23 +13,23 @@ fn string(arg: String) {
|
|||||||
// Your task is to replace `placeholder(…)` with either `string_slice(…)`
|
// Your task is to replace `placeholder(…)` with either `string_slice(…)`
|
||||||
// or `string(…)` depending on what you think each value is.
|
// or `string(…)` depending on what you think each value is.
|
||||||
fn main() {
|
fn main() {
|
||||||
string_slice("blue");
|
placeholder("blue");
|
||||||
|
|
||||||
string("red".to_string());
|
placeholder("red".to_string());
|
||||||
|
|
||||||
string(String::from("hi"));
|
placeholder(String::from("hi"));
|
||||||
|
|
||||||
string("rust is fun!".to_owned());
|
placeholder("rust is fun!".to_owned());
|
||||||
|
|
||||||
string(format!("Interpolation {}", "Station"));
|
placeholder(format!("Interpolation {}", "Station"));
|
||||||
|
|
||||||
// WARNING: This is byte indexing, not character indexing.
|
// WARNING: This is byte indexing, not character indexing.
|
||||||
// Character indexing can be done using `s.chars().nth(INDEX)`.
|
// Character indexing can be done using `s.chars().nth(INDEX)`.
|
||||||
string_slice(&String::from("abc")[0..1]);
|
placeholder(&String::from("abc")[0..1]);
|
||||||
|
|
||||||
string_slice(" hello there ".trim());
|
placeholder(" hello there ".trim());
|
||||||
|
|
||||||
string("Happy Monday!".replace("Mon", "Tues"));
|
placeholder("Happy Monday!".replace("Mon", "Tues"));
|
||||||
|
|
||||||
string("mY sHiFt KeY iS sTiCkY".to_lowercase());
|
placeholder("mY sHiFt KeY iS sTiCkY".to_lowercase());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ mod sausage_factory {
|
|||||||
String::from("Ginger")
|
String::from("Ginger")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn make_sausage() {
|
fn make_sausage() {
|
||||||
get_secret_recipe();
|
get_secret_recipe();
|
||||||
println!("sausage!");
|
println!("sausage!");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,9 +5,6 @@ mod delicious_snacks {
|
|||||||
// TODO: Add the following two `use` statements after fixing them.
|
// TODO: Add the following two `use` statements after fixing them.
|
||||||
// use self::fruits::PEAR as ???;
|
// use self::fruits::PEAR as ???;
|
||||||
// use self::veggies::CUCUMBER as ???;
|
// use self::veggies::CUCUMBER as ???;
|
||||||
|
|
||||||
pub use self::fruits::PEAR as fruit;
|
|
||||||
pub use self::veggies::CUCUMBER as veggie;
|
|
||||||
|
|
||||||
mod fruits {
|
mod fruits {
|
||||||
pub const PEAR: &str = "Pear";
|
pub const PEAR: &str = "Pear";
|
||||||
|
|||||||
@@ -4,8 +4,6 @@
|
|||||||
// TODO: Bring `SystemTime` and `UNIX_EPOCH` from the `std::time` module into
|
// TODO: Bring `SystemTime` and `UNIX_EPOCH` from the `std::time` module into
|
||||||
// your scope. Bonus style points if you can do it with one line!
|
// your scope. Bonus style points if you can do it with one line!
|
||||||
// use ???;
|
// use ???;
|
||||||
use std::time::SystemTime;
|
|
||||||
use std::time::UNIX_EPOCH;
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
match SystemTime::now().duration_since(UNIX_EPOCH) {
|
match SystemTime::now().duration_since(UNIX_EPOCH) {
|
||||||
|
|||||||
@@ -9,11 +9,10 @@ use std::collections::HashMap;
|
|||||||
fn fruit_basket() -> HashMap<String, u32> {
|
fn fruit_basket() -> HashMap<String, u32> {
|
||||||
// TODO: Declare the hash map.
|
// TODO: Declare the hash map.
|
||||||
// let mut basket =
|
// let mut basket =
|
||||||
let mut basket = HashMap::new();
|
|
||||||
// Two bananas are already given for you :)
|
// Two bananas are already given for you :)
|
||||||
basket.insert(String::from("banana"), 2);
|
basket.insert(String::from("banana"), 2);
|
||||||
basket.insert(String::from("apple"), 2);
|
|
||||||
basket.insert(String::from("mango"), 1);
|
|
||||||
// TODO: Put more fruits in your basket.
|
// TODO: Put more fruits in your basket.
|
||||||
|
|
||||||
basket
|
basket
|
||||||
|
|||||||
@@ -28,12 +28,10 @@ fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
|
|||||||
Fruit::Pineapple,
|
Fruit::Pineapple,
|
||||||
];
|
];
|
||||||
|
|
||||||
for _fruit in fruit_kinds {
|
for fruit in fruit_kinds {
|
||||||
// TODO: Insert new fruits if they are not already present in the
|
// TODO: Insert new fruits if they are not already present in the
|
||||||
// basket. Note that you are not allowed to put any type of fruit that's
|
// basket. Note that you are not allowed to put any type of fruit that's
|
||||||
// already present!
|
// already present!
|
||||||
basket.insert(Fruit::Banana, 4);
|
|
||||||
basket.insert(Fruit::Pineapple, 3);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,11 +27,6 @@ fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> {
|
|||||||
let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap();
|
let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap();
|
||||||
let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap();
|
let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap();
|
||||||
|
|
||||||
scores.entry(team_1_name).or_default().goals_scored += team_1_score;
|
|
||||||
scores.entry(team_2_name).or_default().goals_scored += team_2_score;
|
|
||||||
|
|
||||||
scores.entry(team_1_name).or_default().goals_conceded += team_2_score;
|
|
||||||
scores.entry(team_2_name).or_default().goals_conceded += team_1_score;
|
|
||||||
// TODO: Populate the scores table with the extracted details.
|
// TODO: Populate the scores table with the extracted details.
|
||||||
// Keep in mind that goals scored by team 1 will be the number of goals
|
// Keep in mind that goals scored by team 1 will be the number of goals
|
||||||
// conceded by team 2. Similarly, goals scored by team 2 will be the
|
// conceded by team 2. Similarly, goals scored by team 2 will be the
|
||||||
|
|||||||
@@ -4,14 +4,6 @@
|
|||||||
// `hour_of_day` is higher than 23.
|
// `hour_of_day` is higher than 23.
|
||||||
fn maybe_ice_cream(hour_of_day: u16) -> Option<u16> {
|
fn maybe_ice_cream(hour_of_day: u16) -> Option<u16> {
|
||||||
// TODO: Complete the function body.
|
// TODO: Complete the function body.
|
||||||
|
|
||||||
if hour_of_day < 22 {
|
|
||||||
Some(5)
|
|
||||||
} else if hour_of_day <= 23 {
|
|
||||||
Some(0)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
@@ -26,7 +18,7 @@ mod tests {
|
|||||||
fn raw_value() {
|
fn raw_value() {
|
||||||
// TODO: Fix this test. How do you get the value contained in the
|
// TODO: Fix this test. How do you get the value contained in the
|
||||||
// Option?
|
// Option?
|
||||||
let ice_creams = maybe_ice_cream(12).unwrap();
|
let ice_creams = maybe_ice_cream(12);
|
||||||
|
|
||||||
assert_eq!(ice_creams, 5); // Don't change this line.
|
assert_eq!(ice_creams, 5); // Don't change this line.
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,12 +10,8 @@ mod tests {
|
|||||||
let optional_target = Some(target);
|
let optional_target = Some(target);
|
||||||
|
|
||||||
// TODO: Make this an if-let statement whose value is `Some`.
|
// TODO: Make this an if-let statement whose value is `Some`.
|
||||||
//
|
word = optional_target {
|
||||||
// word = optional_target {
|
assert_eq!(word, target);
|
||||||
// assert_eq!(word, target);
|
|
||||||
// }
|
|
||||||
if let Some(word) = optional_target {
|
|
||||||
assert_eq!(word, target)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,13 +29,7 @@ mod tests {
|
|||||||
// TODO: Make this a while-let statement. Remember that `Vec::pop()`
|
// TODO: Make this a while-let statement. Remember that `Vec::pop()`
|
||||||
// adds another layer of `Option`. You can do nested pattern matching
|
// adds another layer of `Option`. You can do nested pattern matching
|
||||||
// in if-let and while-let statements.
|
// in if-let and while-let statements.
|
||||||
//
|
integer = optional_integers.pop() {
|
||||||
// integer = optional_integers.pop() {
|
|
||||||
// assert_eq!(integer, cursor);
|
|
||||||
// cursor -= 1;
|
|
||||||
// }
|
|
||||||
|
|
||||||
while let Some(Some(integer)) = optional_integers.pop() {
|
|
||||||
assert_eq!(integer, cursor);
|
assert_eq!(integer, cursor);
|
||||||
cursor -= 1;
|
cursor -= 1;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,9 +9,7 @@ fn main() {
|
|||||||
|
|
||||||
// TODO: Fix the compiler error by adding something to this match statement.
|
// TODO: Fix the compiler error by adding something to this match statement.
|
||||||
match optional_point {
|
match optional_point {
|
||||||
Some(ref p) => {
|
Some(p) => println!("Coordinates are {},{}", p.x, p.y),
|
||||||
println!("Coordinates are {},{}", p.x, p.y)
|
|
||||||
}
|
|
||||||
_ => panic!("No match!"),
|
_ => panic!("No match!"),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,12 +4,12 @@
|
|||||||
// construct to `Option` that can be used to express error conditions. Change
|
// construct to `Option` that can be used to express error conditions. Change
|
||||||
// the function signature and body to return `Result<String, String>` instead
|
// the function signature and body to return `Result<String, String>` instead
|
||||||
// of `Option<String>`.
|
// of `Option<String>`.
|
||||||
fn generate_nametag_text(name: String) -> Result<String, String> {
|
fn generate_nametag_text(name: String) -> Option<String> {
|
||||||
if name.is_empty() {
|
if name.is_empty() {
|
||||||
// Empty names aren't allowed
|
// Empty names aren't allowed
|
||||||
Err("Empty names aren't allowed".to_string())
|
None
|
||||||
} else {
|
} else {
|
||||||
Ok(format!("Hi! My name is {name}"))
|
Some(format!("Hi! My name is {name}"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
|
|||||||
let cost_per_item = 5;
|
let cost_per_item = 5;
|
||||||
|
|
||||||
// TODO: Handle the error case as described above.
|
// TODO: Handle the error case as described above.
|
||||||
let qty = item_quantity.parse::<i32>()?;
|
let qty = item_quantity.parse::<i32>();
|
||||||
|
|
||||||
Ok(qty * cost_per_item + processing_fee)
|
Ok(qty * cost_per_item + processing_fee)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
|
|||||||
|
|
||||||
// TODO: Fix the compiler error by changing the signature and body of the
|
// TODO: Fix the compiler error by changing the signature and body of the
|
||||||
// `main` function.
|
// `main` function.
|
||||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
fn main() {
|
||||||
let mut tokens = 100;
|
let mut tokens = 100;
|
||||||
let pretend_user_input = "8";
|
let pretend_user_input = "8";
|
||||||
|
|
||||||
@@ -24,10 +24,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
|
|
||||||
if cost > tokens {
|
if cost > tokens {
|
||||||
println!("You can't afford that many!");
|
println!("You can't afford that many!");
|
||||||
Ok(())
|
|
||||||
} else {
|
} else {
|
||||||
tokens -= cost;
|
tokens -= cost;
|
||||||
println!("You now have {tokens} tokens.");
|
println!("You now have {tokens} tokens.");
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::cmp::Ordering;
|
|
||||||
|
|
||||||
#[derive(PartialEq, Debug)]
|
#[derive(PartialEq, Debug)]
|
||||||
enum CreationError {
|
enum CreationError {
|
||||||
Negative,
|
Negative,
|
||||||
@@ -13,11 +11,7 @@ impl PositiveNonzeroInteger {
|
|||||||
fn new(value: i64) -> Result<Self, CreationError> {
|
fn new(value: i64) -> Result<Self, CreationError> {
|
||||||
// TODO: This function shouldn't always return an `Ok`.
|
// TODO: This function shouldn't always return an `Ok`.
|
||||||
// Read the tests below to clarify what should be returned.
|
// Read the tests below to clarify what should be returned.
|
||||||
match value.cmp(&0) {
|
Ok(Self(value as u64))
|
||||||
Ordering::Less => Err(CreationError::Negative),
|
|
||||||
Ordering::Equal => Err(CreationError::Zero),
|
|
||||||
Ordering::Greater => Ok(Self(value as u64)),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ impl PositiveNonzeroInteger {
|
|||||||
|
|
||||||
// TODO: Add the correct return type `Result<(), Box<dyn ???>>`. What can we
|
// TODO: Add the correct return type `Result<(), Box<dyn ???>>`. What can we
|
||||||
// use to describe both errors? Is there a trait which both errors implement?
|
// use to describe both errors? Is there a trait which both errors implement?
|
||||||
fn main() -> Result<(), Box<dyn Error>> {
|
fn main() {
|
||||||
let pretend_user_input = "42";
|
let pretend_user_input = "42";
|
||||||
let x: i64 = pretend_user_input.parse()?;
|
let x: i64 = pretend_user_input.parse()?;
|
||||||
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
|
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ impl PositiveNonzeroInteger {
|
|||||||
fn parse(s: &str) -> Result<Self, ParsePosNonzeroError> {
|
fn parse(s: &str) -> Result<Self, ParsePosNonzeroError> {
|
||||||
// TODO: change this to return an appropriate error instead of panicking
|
// TODO: change this to return an appropriate error instead of panicking
|
||||||
// when `parse()` returns an error.
|
// when `parse()` returns an error.
|
||||||
let x: i64 = s.parse().map_err(ParsePosNonzeroError::ParseInt)?;
|
let x: i64 = s.parse().unwrap();
|
||||||
Self::new(x).map_err(ParsePosNonzeroError::Creation)
|
Self::new(x).map_err(ParsePosNonzeroError::Creation)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ fn main() {
|
|||||||
// TODO: Fix the compiler error by annotating the type of the vector
|
// TODO: Fix the compiler error by annotating the type of the vector
|
||||||
// `Vec<T>`. Choose `T` as some integer type that can be created from
|
// `Vec<T>`. Choose `T` as some integer type that can be created from
|
||||||
// `u8` and `i8`.
|
// `u8` and `i8`.
|
||||||
let mut numbers: Vec<i16> = Vec::new();
|
let mut numbers = Vec::new();
|
||||||
|
|
||||||
// Don't change the lines below.
|
// Don't change the lines below.
|
||||||
let n1: u8 = 42;
|
let n1: u8 = 42;
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
// This powerful wrapper provides the ability to store a positive integer value.
|
// This powerful wrapper provides the ability to store a positive integer value.
|
||||||
// TODO: Rewrite it using a generic so that it supports wrapping ANY type.
|
// TODO: Rewrite it using a generic so that it supports wrapping ANY type.
|
||||||
struct Wrapper<T> {
|
struct Wrapper {
|
||||||
value: T,
|
value: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Adapt the struct's implementation to be generic over the wrapped value.
|
// TODO: Adapt the struct's implementation to be generic over the wrapped value.
|
||||||
impl<T> Wrapper<T> {
|
impl Wrapper {
|
||||||
fn new(value: T) -> Self {
|
fn new(value: u32) -> Self {
|
||||||
Wrapper { value }
|
Wrapper { value }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,9 +6,6 @@ trait AppendBar {
|
|||||||
|
|
||||||
impl AppendBar for String {
|
impl AppendBar for String {
|
||||||
// TODO: Implement `AppendBar` for the type `String`.
|
// TODO: Implement `AppendBar` for the type `String`.
|
||||||
fn append_bar(self) -> Self {
|
|
||||||
self + &String::from("Bar")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -4,12 +4,6 @@ trait AppendBar {
|
|||||||
|
|
||||||
// TODO: Implement the trait `AppendBar` for a vector of strings.
|
// TODO: Implement the trait `AppendBar` for a vector of strings.
|
||||||
// `append_bar` should push the string "Bar" into the vector.
|
// `append_bar` should push the string "Bar" into the vector.
|
||||||
impl AppendBar for Vec<String> {
|
|
||||||
fn append_bar(mut self) -> Self {
|
|
||||||
self.push(String::from("Bar"));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
// You can optionally experiment here.
|
// You can optionally experiment here.
|
||||||
|
|||||||
@@ -3,9 +3,7 @@ trait Licensed {
|
|||||||
// implementors like the two structs below can share that default behavior
|
// implementors like the two structs below can share that default behavior
|
||||||
// without repeating the function.
|
// without repeating the function.
|
||||||
// The default license information should be the string "Default license".
|
// The default license information should be the string "Default license".
|
||||||
fn licensing_info(&self) -> String {
|
fn licensing_info(&self) -> String;
|
||||||
String::from("Default license")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct SomeSoftware {
|
struct SomeSoftware {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ impl Licensed for SomeSoftware {}
|
|||||||
impl Licensed for OtherSoftware {}
|
impl Licensed for OtherSoftware {}
|
||||||
|
|
||||||
// TODO: Fix the compiler error by only changing the signature of this function.
|
// TODO: Fix the compiler error by only changing the signature of this function.
|
||||||
fn compare_license_types(software1: impl Licensed, software2: impl Licensed) -> bool {
|
fn compare_license_types(software1: ???, software2: ???) -> bool {
|
||||||
software1.licensing_info() == software2.licensing_info()
|
software1.licensing_info() == software2.licensing_info()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ impl SomeTrait for OtherStruct {}
|
|||||||
impl OtherTrait for OtherStruct {}
|
impl OtherTrait for OtherStruct {}
|
||||||
|
|
||||||
// TODO: Fix the compiler error by only changing the signature of this function.
|
// TODO: Fix the compiler error by only changing the signature of this function.
|
||||||
fn some_func(item: impl SomeTrait + OtherTrait) -> bool {
|
fn some_func(item: ???) -> bool {
|
||||||
item.some_function() && item.other_function()
|
item.some_function() && item.other_function()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// not own their own data. What if their owner goes out of scope?
|
// not own their own data. What if their owner goes out of scope?
|
||||||
|
|
||||||
// TODO: Fix the compiler error by updating the function signature.
|
// TODO: Fix the compiler error by updating the function signature.
|
||||||
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
|
fn longest(x: &str, y: &str) -> &str {
|
||||||
if x.len() > y.len() {
|
if x.len() > y.len() {
|
||||||
x
|
x
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -15,6 +15,6 @@ fn main() {
|
|||||||
{
|
{
|
||||||
let string2 = String::from("xyz");
|
let string2 = String::from("xyz");
|
||||||
result = longest(&string1, &string2);
|
result = longest(&string1, &string2);
|
||||||
println!("The longest string is '{result}'");
|
|
||||||
}
|
}
|
||||||
|
println!("The longest string is '{result}'");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
// Lifetimes are also needed when structs hold references.
|
// Lifetimes are also needed when structs hold references.
|
||||||
|
|
||||||
// TODO: Fix the compiler errors about the struct.
|
// TODO: Fix the compiler errors about the struct.
|
||||||
struct Book<'a> {
|
struct Book {
|
||||||
author: &'a str,
|
author: &str,
|
||||||
title: &'a str,
|
title: &str,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -13,12 +13,11 @@ fn main() {
|
|||||||
mod tests {
|
mod tests {
|
||||||
// TODO: Import `is_even`. You can use a wildcard to import everything in
|
// TODO: Import `is_even`. You can use a wildcard to import everything in
|
||||||
// the outer module.
|
// the outer module.
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn you_can_assert() {
|
fn you_can_assert() {
|
||||||
// TODO: Test the function `is_even` with some values.
|
// TODO: Test the function `is_even` with some values.
|
||||||
assert!(!is_even(1));
|
assert!();
|
||||||
assert!(is_even(12));
|
assert!();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,9 +15,9 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn you_can_assert_eq() {
|
fn you_can_assert_eq() {
|
||||||
// TODO: Test the function `power_of_2` with some values.
|
// TODO: Test the function `power_of_2` with some values.
|
||||||
assert_eq!(power_of_2(2), 4);
|
assert_eq!();
|
||||||
assert_eq!(power_of_2(3), 8);
|
assert_eq!();
|
||||||
assert_eq!(power_of_2(10), 1024);
|
assert_eq!();
|
||||||
assert_eq!(power_of_2(42), 4398046511104);
|
assert_eq!();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,14 +29,13 @@ mod tests {
|
|||||||
// TODO: This test should check if the rectangle has the size that we
|
// TODO: This test should check if the rectangle has the size that we
|
||||||
// pass to its constructor.
|
// pass to its constructor.
|
||||||
let rect = Rectangle::new(10, 20);
|
let rect = Rectangle::new(10, 20);
|
||||||
assert_eq!(rect.width, 10); // Check width
|
assert_eq!(todo!(), 10); // Check width
|
||||||
assert_eq!(rect.height, 20); // Check height
|
assert_eq!(todo!(), 20); // Check height
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: This test should check if the program panics when we try to create
|
// TODO: This test should check if the program panics when we try to create
|
||||||
// a rectangle with negative width.
|
// a rectangle with negative width.
|
||||||
#[test]
|
#[test]
|
||||||
#[should_panic]
|
|
||||||
fn negative_width() {
|
fn negative_width() {
|
||||||
let _rect = Rectangle::new(-10, 10);
|
let _rect = Rectangle::new(-10, 10);
|
||||||
}
|
}
|
||||||
@@ -44,7 +43,6 @@ mod tests {
|
|||||||
// TODO: This test should check if the program panics when we try to create
|
// TODO: This test should check if the program panics when we try to create
|
||||||
// a rectangle with negative height.
|
// a rectangle with negative height.
|
||||||
#[test]
|
#[test]
|
||||||
#[should_panic]
|
|
||||||
fn negative_height() {
|
fn negative_height() {
|
||||||
let _rect = Rectangle::new(10, -10);
|
let _rect = Rectangle::new(10, -10);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,13 +13,13 @@ mod tests {
|
|||||||
let my_fav_fruits = &["banana", "custard apple", "avocado", "peach", "raspberry"];
|
let my_fav_fruits = &["banana", "custard apple", "avocado", "peach", "raspberry"];
|
||||||
|
|
||||||
// TODO: Create an iterator over the slice.
|
// TODO: Create an iterator over the slice.
|
||||||
let mut fav_fruits_iterator = my_fav_fruits.iter();
|
let mut fav_fruits_iterator = todo!();
|
||||||
|
|
||||||
assert_eq!(fav_fruits_iterator.next(), Some(&"banana"));
|
assert_eq!(fav_fruits_iterator.next(), Some(&"banana"));
|
||||||
assert_eq!(fav_fruits_iterator.next(), Some(&"custard apple")); // TODO: Replace `todo!()`
|
assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()`
|
||||||
assert_eq!(fav_fruits_iterator.next(), Some(&"avocado"));
|
assert_eq!(fav_fruits_iterator.next(), Some(&"avocado"));
|
||||||
assert_eq!(fav_fruits_iterator.next(), Some(&"peach")); // TODO: Replace `todo!()`
|
assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()`
|
||||||
assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry"));
|
assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry"));
|
||||||
assert_eq!(fav_fruits_iterator.next(), None); // TODO: Replace `todo!()`
|
assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,13 @@
|
|||||||
// In this exercise, you'll learn some of the unique advantages that iterators
|
// In this exercise, you'll learn some of the unique advantages that iterators
|
||||||
// can offer.
|
// can offer.
|
||||||
|
|
||||||
// I failed.
|
|
||||||
|
|
||||||
// TODO: Complete the `capitalize_first` function.
|
// TODO: Complete the `capitalize_first` function.
|
||||||
// "hello" -> "Hello"
|
// "hello" -> "Hello"
|
||||||
fn capitalize_first(input: &str) -> String {
|
fn capitalize_first(input: &str) -> String {
|
||||||
let mut chars = input.chars();
|
let mut chars = input.chars();
|
||||||
match chars.next() {
|
match chars.next() {
|
||||||
None => String::new(),
|
None => String::new(),
|
||||||
Some(first) => first.to_uppercase().to_string() + chars.as_str(),
|
Some(first) => todo!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,7 +16,6 @@ fn capitalize_first(input: &str) -> String {
|
|||||||
// ["hello", "world"] -> ["Hello", "World"]
|
// ["hello", "world"] -> ["Hello", "World"]
|
||||||
fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
|
fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
|
||||||
// ???
|
// ???
|
||||||
words.iter().map(|word| capitalize_first(word)).collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Apply the `capitalize_first` function again to a slice of string
|
// TODO: Apply the `capitalize_first` function again to a slice of string
|
||||||
@@ -26,7 +23,6 @@ fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
|
|||||||
// ["hello", " ", "world"] -> "Hello World"
|
// ["hello", " ", "world"] -> "Hello World"
|
||||||
fn capitalize_words_string(words: &[&str]) -> String {
|
fn capitalize_words_string(words: &[&str]) -> String {
|
||||||
// ???
|
// ???
|
||||||
words.iter().map(|word| capitalize_first(word)).collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -11,31 +11,21 @@ enum DivisionError {
|
|||||||
// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
|
// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
|
||||||
// Otherwise, return a suitable error.
|
// Otherwise, return a suitable error.
|
||||||
fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
|
fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
|
||||||
if b == 0 {
|
todo!();
|
||||||
Err(DivisionError::DivideByZero)
|
|
||||||
} else if b == -1 && a == i64::MIN {
|
|
||||||
Err(DivisionError::IntegerOverflow)
|
|
||||||
} else if a % b == 0 {
|
|
||||||
Ok(a / b)
|
|
||||||
} else {
|
|
||||||
Err(DivisionError::NotDivisible)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Add the correct return type and complete the function body.
|
// TODO: Add the correct return type and complete the function body.
|
||||||
// Desired output: `Ok([1, 11, 1426, 3])`
|
// Desired output: `Ok([1, 11, 1426, 3])`
|
||||||
fn result_with_list() -> Result<Vec<i64>, DivisionError> {
|
fn result_with_list() {
|
||||||
let numbers = [27, 297, 38502, 81];
|
let numbers = [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));
|
||||||
division_results.collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Add the correct return type and complete the function body.
|
// TODO: Add the correct return type and complete the function body.
|
||||||
// Desired output: `[Ok(1), Ok(11), Ok(1426), Ok(3)]`
|
// Desired output: `[Ok(1), Ok(11), Ok(1426), Ok(3)]`
|
||||||
fn list_of_results() -> Vec<Result<i64, DivisionError>> {
|
fn list_of_results() {
|
||||||
let numbers = [27, 297, 38502, 81];
|
let numbers = [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));
|
||||||
division_results.collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -10,8 +10,6 @@ fn factorial(num: u64) -> u64 {
|
|||||||
// - additional variables
|
// - additional variables
|
||||||
// For an extra challenge, don't use:
|
// For an extra challenge, don't use:
|
||||||
// - recursion
|
// - recursion
|
||||||
|
|
||||||
(1..=num).product()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
@@ -11,18 +11,6 @@
|
|||||||
// TODO: Write a function that calculates the price of an order of apples given
|
// TODO: Write a function that calculates the price of an order of apples given
|
||||||
// the quantity bought.
|
// the quantity bought.
|
||||||
// fn calculate_price_of_apples(???) -> ??? { ??? }
|
// fn calculate_price_of_apples(???) -> ??? { ??? }
|
||||||
fn calculate_price_of_apples(apples: i32) -> i32 {
|
|
||||||
let mut cost: i32 = 2;
|
|
||||||
|
|
||||||
if apples > 40 {
|
|
||||||
cost = 1;
|
|
||||||
cost *= apples;
|
|
||||||
cost
|
|
||||||
} else {
|
|
||||||
cost *= apples;
|
|
||||||
cost
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
// You can optionally experiment here.
|
// You can optionally experiment here.
|
||||||
|
|||||||
@@ -28,25 +28,6 @@ mod my_module {
|
|||||||
|
|
||||||
// TODO: Complete the function as described above.
|
// TODO: Complete the function as described above.
|
||||||
// pub fn transformer(input: ???) -> ??? { ??? }
|
// pub fn transformer(input: ???) -> ??? { ??? }
|
||||||
|
|
||||||
pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
|
|
||||||
let mut output = Vec::new();
|
|
||||||
for (s, cmd) in input {
|
|
||||||
let transformed = match cmd {
|
|
||||||
Command::Uppercase => s.to_uppercase(),
|
|
||||||
Command::Trim => s.trim().to_owned(),
|
|
||||||
Command::Append(n) => {
|
|
||||||
let mut out = s;
|
|
||||||
for _ in 0..n {
|
|
||||||
out.push_str("bar");
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
};
|
|
||||||
output.push(transformed)
|
|
||||||
}
|
|
||||||
output
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
@@ -58,7 +39,6 @@ mod tests {
|
|||||||
// TODO: What do we need to import to have `transformer` in scope?
|
// TODO: What do we need to import to have `transformer` in scope?
|
||||||
// use ???;
|
// use ???;
|
||||||
use super::Command;
|
use super::Command;
|
||||||
use crate::my_module::transformer;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn it_works() {
|
fn it_works() {
|
||||||
|
|||||||
@@ -12,18 +12,18 @@
|
|||||||
// block to support alphabetical report cards in addition to numerical ones.
|
// block to support alphabetical report cards in addition to numerical ones.
|
||||||
|
|
||||||
// TODO: Adjust the struct as described above.
|
// TODO: Adjust the struct as described above.
|
||||||
struct ReportCard<T> {
|
struct ReportCard {
|
||||||
grade: T,
|
grade: f32,
|
||||||
student_name: String,
|
student_name: String,
|
||||||
student_age: u8,
|
student_age: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Adjust the impl block as described above.
|
// TODO: Adjust the impl block as described above.
|
||||||
impl<T: std::fmt::Display> ReportCard<T> {
|
impl ReportCard {
|
||||||
fn print(&self) -> String {
|
fn print(&self) -> String {
|
||||||
format!(
|
format!(
|
||||||
"{} ({}) - achieved a grade of {}",
|
"{} ({}) - achieved a grade of {}",
|
||||||
self.student_name, self.student_age, self.grade,
|
&self.student_name, &self.student_age, &self.grade,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user