progress 50 percent

Change-Id: I8c926bd37d7fefc9143b0accdb1a165a9c1063df
This commit is contained in:
murasame 2023-05-19 17:41:56 +08:00
parent f2de12aa34
commit 3cc91daba5
52 changed files with 308 additions and 233 deletions

View File

@ -3,25 +3,20 @@
// and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively.
// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
// Obtain the number of bytes (not characters) in the given argument.
// TODO: Add the AsRef trait appropriately as a trait bound.
fn byte_counter<T>(arg: T) -> usize {
fn byte_counter<T>(arg: T) -> usize where T: AsRef<str> {
arg.as_ref().as_bytes().len()
}
// Obtain the number of characters (not bytes) in the given argument.
// TODO: Add the AsRef trait appropriately as a trait bound.
fn char_counter<T>(arg: T) -> usize {
fn char_counter<T>(arg: T) -> usize where T: AsRef<str> {
arg.as_ref().chars().count()
}
// Squares a number using as_mut().
// TODO: Add the appropriate trait bound.
fn num_sq<T>(arg: &mut T) {
// TODO: Implement the function body.
???
fn num_sq<T>(arg: &mut T) where T: AsMut<u32> {
let v = arg.as_mut();
*v = (*v) * (*v)
}
#[cfg(test)]

View File

@ -35,10 +35,34 @@ 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.is_empty() {
return Default::default();
}
let vals = s.split(",");
let mut idx = 0;
let mut name: &str = "";
let mut age: usize = 0;
for val in vals {
if idx > 2 {
return Default::default();
}
if idx == 0 {
name = val;
} else if idx == 1 {
if let Ok(age_num) = val.parse::<usize>() {
age = age_num;
} else {
return Default::default();
}
}
idx += 1;
}
if idx != 2 || name.is_empty() {
return Default::default();
}
return Person { name: String::from(name), age };
}
}
@ -54,6 +78,7 @@ fn main() {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
// Test that the default person is 30 year old John
@ -61,6 +86,7 @@ mod tests {
assert_eq!(dp.name, "John");
assert_eq!(dp.age, 30);
}
#[test]
fn test_bad_convert() {
// Test that John is returned when bad string is provided
@ -68,6 +94,7 @@ mod tests {
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_good_convert() {
// Test that "Mark,20" works
@ -75,6 +102,7 @@ mod tests {
assert_eq!(p.name, "Mark");
assert_eq!(p.age, 20);
}
#[test]
fn test_bad_age() {
// Test that "Mark,twenty" will return the default person due to an error in parsing age

View File

@ -28,8 +28,6 @@ enum ParsePersonError {
ParseInt(ParseIntError),
}
// I AM NOT DONE
// Steps:
// 1. If the length of the provided string is 0, an error should be returned
// 2. Split the given string on the commas present in it
@ -46,6 +44,36 @@ enum ParsePersonError {
impl FromStr for Person {
type Err = ParsePersonError;
fn from_str(s: &str) -> Result<Person, Self::Err> {
if s.is_empty() {
return Err(ParsePersonError::Empty);
}
let vals = s.split(",");
let mut idx = 0;
let mut name: &str = "";
let mut age: usize = 0;
for val in vals {
if idx > 2 {
return Err(ParsePersonError::BadLen);
}
if idx == 0 {
name = val;
} else if idx == 1 {
match val.parse::<usize>() {
Ok(age_num) => { age = age_num }
Err(err) => {
return Err(ParsePersonError::ParseInt(err));
}
}
}
idx += 1;
}
if idx != 2 {
return Err(ParsePersonError::BadLen);
}
if name.is_empty() {
return Err(ParsePersonError::NoName);
}
return Ok(Person { name: String::from(name), age });
}
}
@ -62,6 +90,7 @@ mod tests {
fn empty_input() {
assert_eq!("".parse::<Person>(), Err(ParsePersonError::Empty));
}
#[test]
fn good_input() {
let p = "John,32".parse::<Person>();
@ -70,6 +99,7 @@ mod tests {
assert_eq!(p.name, "John");
assert_eq!(p.age, 32);
}
#[test]
fn missing_age() {
assert!(matches!(

View File

@ -7,6 +7,9 @@
use std::convert::{TryFrom, TryInto};
const LEFT_MARGIN: i16 = 0;
const RIGHT_MARGIN: i16 = 255;
#[derive(Debug, PartialEq)]
struct Color {
red: u8,
@ -23,8 +26,6 @@ enum IntoColorError {
IntConversion,
}
// I AM NOT DONE
// Your task is to complete this implementation
// and return an Ok result of inner type Color.
// You need to create an implementation for a tuple of three integers,
@ -38,6 +39,12 @@ enum IntoColorError {
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
if tuple.0 < LEFT_MARGIN || tuple.0 > RIGHT_MARGIN ||
tuple.1 < LEFT_MARGIN || tuple.1 > RIGHT_MARGIN ||
tuple.2 < LEFT_MARGIN || tuple.2 > RIGHT_MARGIN {
return Err(IntoColorError::IntConversion);
}
return Ok(Color { red: tuple.0 as u8, green: tuple.1 as u8, blue: tuple.2 as u8 });
}
}
@ -45,6 +52,27 @@ impl TryFrom<(i16, i16, i16)> for Color {
impl TryFrom<[i16; 3]> for Color {
type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
let mut red: u8 = 0;
let mut green: u8 = 0;
let mut blue: u8 = 0;
for (idx, num) in arr.iter().enumerate() {
if idx > 2 {
return Err(IntoColorError::BadLen);
}
if num < &LEFT_MARGIN || num > &RIGHT_MARGIN {
return Err(IntoColorError::IntConversion);
}
if idx == 0 {
red = *num as u8;
}
if idx == 1 {
green = *num as u8;
}
if idx == 2 {
blue = *num as u8;
}
}
return Ok(Color { red, green, blue });
}
}
@ -52,6 +80,30 @@ impl TryFrom<[i16; 3]> for Color {
impl TryFrom<&[i16]> for Color {
type Error = IntoColorError;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
if slice.len() != 3 {
return Err(IntoColorError::BadLen);
}
let mut red: u8 = 0;
let mut green: u8 = 0;
let mut blue: u8 = 0;
for (idx, num) in slice.iter().enumerate() {
if idx > 2 {
return Err(IntoColorError::BadLen);
}
if num < &LEFT_MARGIN || num > &RIGHT_MARGIN {
return Err(IntoColorError::IntConversion);
}
if idx == 0 {
red = *num as u8;
}
if idx == 1 {
green = *num as u8;
}
if idx == 2 {
blue = *num as u8;
}
}
return Ok(Color { red, green, blue });
}
}
@ -84,6 +136,7 @@ mod tests {
Err(IntoColorError::IntConversion)
);
}
#[test]
fn test_tuple_out_of_range_negative() {
assert_eq!(
@ -91,6 +144,7 @@ mod tests {
Err(IntoColorError::IntConversion)
);
}
#[test]
fn test_tuple_sum() {
assert_eq!(
@ -98,6 +152,7 @@ mod tests {
Err(IntoColorError::IntConversion)
);
}
#[test]
fn test_tuple_correct() {
let c: Result<Color, _> = (183, 65, 14).try_into();
@ -107,25 +162,29 @@ mod tests {
Color {
red: 183,
green: 65,
blue: 14
blue: 14,
}
);
}
#[test]
fn test_array_out_of_range_positive() {
let c: Result<Color, _> = [1000, 10000, 256].try_into();
assert_eq!(c, Err(IntoColorError::IntConversion));
}
#[test]
fn test_array_out_of_range_negative() {
let c: Result<Color, _> = [-10, -256, -1].try_into();
assert_eq!(c, Err(IntoColorError::IntConversion));
}
#[test]
fn test_array_sum() {
let c: Result<Color, _> = [-1, 255, 255].try_into();
assert_eq!(c, Err(IntoColorError::IntConversion));
}
#[test]
fn test_array_correct() {
let c: Result<Color, _> = [183, 65, 14].try_into();
@ -135,10 +194,11 @@ mod tests {
Color {
red: 183,
green: 65,
blue: 14
blue: 14,
}
);
}
#[test]
fn test_slice_out_of_range_positive() {
let arr = [10000, 256, 1000];
@ -147,6 +207,7 @@ mod tests {
Err(IntoColorError::IntConversion)
);
}
#[test]
fn test_slice_out_of_range_negative() {
let arr = [-256, -1, -10];
@ -155,6 +216,7 @@ mod tests {
Err(IntoColorError::IntConversion)
);
}
#[test]
fn test_slice_sum() {
let arr = [-1, 255, 255];
@ -163,6 +225,7 @@ mod tests {
Err(IntoColorError::IntConversion)
);
}
#[test]
fn test_slice_correct() {
let v = vec![183, 65, 14];
@ -173,15 +236,17 @@ mod tests {
Color {
red: 183,
green: 65,
blue: 14
blue: 14,
}
);
}
#[test]
fn test_slice_excess_length() {
let v = vec![0, 0, 0, 0];
assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen));
}
#[test]
fn test_slice_insufficient_length() {
let v = vec![0, 0];

View File

@ -6,11 +6,9 @@
// and returns the proper type.
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn average(values: &[f64]) -> f64 {
let total = values.iter().sum::<f64>();
total / values.len()
total / (values.len() as f64)
}
fn main() {

View File

@ -1,11 +1,12 @@
// enums1.rs
// No hints this time! ;)
// I AM NOT DONE
// No hints this time! :)
#[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,12 @@
// enums2.rs
// Execute `rustlings hint enums2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[derive(Debug)]
enum Message {
// TODO: define the different variants used below
Move { x: usize, y: usize },
Echo(String),
ChangeColor(u8, u8, u8),
Quit,
}
impl Message {

View File

@ -2,10 +2,11 @@
// Address all the TODOs to make the tests pass!
// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a hint.
// 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,
}
struct Point {
@ -37,8 +38,18 @@ impl State {
}
fn process(&mut self, message: Message) {
// TODO: create a match expression to process the different message variants
// Remember: When passing a tuple as a function argument, you'll need extra parentheses: fn function((t, u, p, l, e))
match message {
Message::ChangeColor(r, g, b) => {
self.change_color((r, g, b))
}
Message::Move(point) => {
self.move_position(point)
}
Message::Echo(s) => {
self.echo(s)
}
Message::Quit => { self.quit() }
}
}
}

View File

@ -1,8 +1,8 @@
// functions1.rs
// Execute `rustlings hint functions1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
call_me();
}
fn call_me() {}

View File

@ -1,13 +1,11 @@
// functions2.rs
// Execute `rustlings hint functions2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
call_me(3);
}
fn call_me(num:) {
fn call_me(num: i32) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}

View File

@ -1,10 +1,8 @@
// functions3.rs
// Execute `rustlings hint functions3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
call_me();
call_me(10);
}
fn call_me(num: u32) {

View File

@ -7,14 +7,12 @@
// in the signatures for now. If anything, this is a good way to peek ahead
// to future exercises!)
// 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
// Execute `rustlings hint functions5` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
let answer = square(3);
println!("The square of 3 is {}", answer);
}
fn square(num: i32) -> i32 {
num * num;
num * num
}

View File

@ -10,17 +10,15 @@
//
// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a hint.
// 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"), 3);
basket.insert(String::from("pear"), 5);
basket
}

View File

@ -13,8 +13,6 @@
//
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
use std::collections::HashMap;
#[derive(Hash, PartialEq, Eq)]
@ -36,9 +34,10 @@ fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
];
for fruit in fruit_kinds {
// 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 already
// present!
if basket.contains_key(&fruit) {
continue;
}
basket.insert(fruit, 10);
}
}

View File

@ -14,8 +14,6 @@
// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
use std::collections::HashMap;
// A structure to store team name and its goal details.
@ -35,11 +33,20 @@ fn build_scores_table(results: String) -> HashMap<String, Team> {
let team_1_score: u8 = v[2].parse().unwrap();
let team_2_name = v[1].to_string();
let team_2_score: u8 = v[3].parse().unwrap();
// TODO: Populate the scores table with details extracted from the
// current line. Keep in mind that goals scored by team_1
// will be the number of goals conceded from team_2, and similarly
// goals scored by team_2 will be the number of goals conceded by
// team_1.
if scores.contains_key(team_1_name.as_str()) {
let mut team1 = scores.get_mut(team_1_name.as_str()).unwrap();
team1.goals_scored += team_1_score;
team1.goals_conceded += team_2_score;
} else {
scores.insert(team_1_name.clone(), Team { name: team_1_name.clone(), goals_scored: team_1_score, goals_conceded: team_2_score });
}
if scores.contains_key(team_2_name.as_str()) {
let mut team2 = scores.get_mut(team_2_name.as_str()).unwrap();
team2.goals_scored += team_2_score;
team2.goals_conceded += team_1_score;
} else {
scores.insert(team_2_name.clone(), Team { name: team_2_name.clone(), goals_scored: team_2_score, goals_conceded: team_1_score });
}
}
scores
}

View File

@ -1,13 +1,16 @@
// if1.rs
// Execute `rustlings hint if1` or use the `hint` watch subcommand for a hint.
// 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
return if a > b {
a
} else {
b
};
}
// Don't mind this for now :)

View File

@ -4,13 +4,13 @@
// Step 2: Get the bar_for_fuzz and default_to_baz tests passing!
// Execute `rustlings hint if2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
pub fn foo_if_fizz(fizzish: &str) -> &str {
if fizzish == "fizz" {
"foo"
} else if fizzish == "fuzz" {
"bar"
} else {
1
"baz"
}
}

View File

@ -9,8 +9,6 @@
// when you change one of the lines below! Try adding a `println!` line, or try changing
// what it outputs in your terminal. Try removing a semicolon and see what happens!
// I AM NOT DONE
fn main() {
println!("Hello and");
println!(r#" welcome to... "#);

View File

@ -2,8 +2,6 @@
// Make the code print a greeting to the world.
// Execute `rustlings hint intro2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
println!("Hello {}!");
println!("Hello {}!", "World");
}

View File

@ -1,15 +1,13 @@
// modules1.rs
// Execute `rustlings hint modules1` or use the `hint` watch subcommand for a hint.
// 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,12 +3,9 @@
// 'use' and 'as' keywords. Fix these 'use' statements to make the code compile.
// Execute `rustlings hint modules2` or use the `hint` watch subcommand for a hint.
// 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,7 @@
// from the std::time module. Bonus style points if you can do it with one line!
// Execute `rustlings hint modules3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
// TODO: Complete this use statement
use ???
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
match SystemTime::now().duration_since(UNIX_EPOCH) {

View File

@ -1,12 +1,10 @@
// move_semantics1.rs
// Execute `rustlings hint move_semantics1` or use the `hint` watch subcommand for a hint.
// 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

@ -5,28 +5,23 @@
// vec0 has length 3 content `[22, 44, 66]`
// vec1 has length 4 content `[22, 44, 66, 88]`
// I AM NOT DONE
fn main() {
let vec0 = Vec::new();
let mut vec0 = Vec::new();
// Do not move the following line!
let mut vec1 = fill_vec(vec0);
fill_vec(&mut vec0);
// Do not change the following line!
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);
let mut vec1 = vec0.clone();
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: &mut Vec<i32>) {
vec.push(22);
vec.push(44);
vec.push(66);
vec
}

View File

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

View File

@ -4,12 +4,8 @@
// function.
// Execute `rustlings hint move_semantics4` or use the `hint` watch subcommand for a hint.
// 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 takes `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

@ -3,13 +3,15 @@
// adding, changing or removing any of them.
// Execute `rustlings hint move_semantics5` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
let mut x = 100;
let y = &mut x;
let z = &mut x;
*y += 100;
*z += 1000;
{
let y = &mut x;
*y += 100;
}
{
let z = &mut x;
*z += 1000;
}
assert_eq!(x, 1200);
}

View File

@ -2,24 +2,22 @@
// Execute `rustlings hint move_semantics6` or use the `hint` watch subcommand for a hint.
// You can't change anything except adding or removing references.
// I AM NOT DONE
fn main() {
let data = "Rust is great!".to_string();
get_char(data);
get_char(&data);
string_uppercase(&data);
string_uppercase(data);
}
// Should not take ownership
fn get_char(data: String) -> char {
fn get_char(data: &String) -> char {
data.chars().last().unwrap()
}
// Should take ownership
fn string_uppercase(mut data: &String) {
data = &data.to_uppercase();
fn string_uppercase(mut data: String) {
data = data.to_uppercase();
println!("{}", data);
}

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,7 +10,7 @@ fn main() {
println!("Good morning!");
}
let // Finish the rest of this line like the example! Or make it be false!
let is_evening = false; // Finish the rest of this line like the example! Or make it be false!
if is_evening {
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`)
@ -18,7 +16,7 @@ fn main() {
println!("Neither alphabetic nor numeric!");
}
let // Finish this line like the example! What's your favorite character?
let your_character = 'B'; // 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() {

View File

@ -2,10 +2,8 @@
// Create an array with at least 100 elements in it where the ??? is.
// Execute `rustlings hint primitive_types3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
let a = ???
let a: &[i32; 5] = &[1, 2, 3, 4, 5];
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` or use the `hint` watch subcommand for a hint.
// 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` or use the `hint` watch subcommand for a hint.
// 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,12 @@
// You can put the expression for the second element where ??? is so that the test passes.
// Execute `rustlings hint primitive_types6` or use the `hint` watch subcommand for a hint.
// 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!")
"This is not the 2nd number in the tuple!")
}

View File

@ -10,10 +10,14 @@
// Write a function that calculates the price of an order of apples given
// the quantity bought. No hints this time!
// I AM NOT DONE
// Put your function here!
// fn calculate_price_of_apples {
fn calculate_price_of_apples(num: i32) -> i32 {
return if num <= 40 {
num * 2
} else {
num
};
}
// Don't modify this function!
#[test]

View File

@ -18,8 +18,6 @@
// - The output element is going to be a Vector of strings.
// No hints this time!
// I AM NOT DONE
pub enum Command {
Uppercase,
Trim,
@ -29,12 +27,24 @@ pub enum Command {
mod my_module {
use super::Command;
// TODO: Complete the function signature!
pub fn transformer(input: ???) -> ??? {
// TODO: Complete the output declaration!
let mut output: ??? = vec![];
for (string, command) in input.iter() {
// TODO: Complete the function body. You can do it!
pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
let mut output: Vec<String> = vec![];
for (s, cmd) in input.iter() {
let mut string = s.clone();
match cmd {
Command::Uppercase => {
string = string.to_uppercase();
}
Command::Trim => {
string = string.trim().to_string();
}
Command::Append(us) => {
for i in 0..(*us as i32) {
string.push_str("bar");
}
}
}
output.push(string);
}
output
}
@ -42,8 +52,7 @@ mod my_module {
#[cfg(test)]
mod tests {
// TODO: What do we need to import to have `transformer` in scope?
use ???;
use super::my_module::transformer;
use super::Command;
#[test]

View File

@ -2,13 +2,11 @@
// Make me compile without changing the function signature!
// Execute `rustlings hint strings1` or use the `hint` watch subcommand for a hint.
// 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` or use the `hint` watch subcommand for a hint.
// 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.as_str()) {
println!("That is a color word I know!");
} else {
println!("That is not a color word I know.");

View File

@ -1,21 +1,18 @@
// strings3.rs
// Execute `rustlings hint strings3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn trim_me(input: &str) -> String {
// TODO: Remove whitespace from both ends of a string!
???
input.trim().to_string()
}
fn compose_me(input: &str) -> String {
// TODO: Add " world!" to the string! There's multiple ways to do this!
???
let mut owned_str = String::from(input.clone());
owned_str.push_str(" world!");
owned_str
}
fn replace_me(input: &str) -> String {
// TODO: Replace "cars" in the string with "balloons"!
???
input.replace("car", "balloon").to_string()
}
#[cfg(test)]

View File

@ -6,24 +6,24 @@
// before the parentheses on each line. If you're right, it will compile!
// No hints this time!
// I AM NOT DONE
fn string_slice(arg: &str) {
println!("{}", arg);
}
fn string(arg: String) {
println!("{}", arg);
}
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_slice("nice weather".into());
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

@ -2,13 +2,13 @@
// Address all the TODOs to make the tests pass!
// Execute `rustlings hint structs1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
struct ColorClassicStruct {
// TODO: Something goes here
red: u8,
green: u8,
blue: u8,
}
struct ColorTupleStruct(/* TODO: Something goes here */);
struct ColorTupleStruct(u8, u8, u8);
#[derive(Debug)]
struct UnitLikeStruct;
@ -19,8 +19,7 @@ mod tests {
#[test]
fn classic_c_structs() {
// TODO: Instantiate a classic c struct!
// let green =
let green = ColorClassicStruct { red: 0, green: 255, blue: 0 };
assert_eq!(green.red, 0);
assert_eq!(green.green, 255);
@ -29,8 +28,7 @@ mod tests {
#[test]
fn tuple_structs() {
// TODO: Instantiate a tuple struct!
// let green =
let green = ColorTupleStruct(0, 255, 0);
assert_eq!(green.0, 0);
assert_eq!(green.1, 255);
@ -39,8 +37,7 @@ mod tests {
#[test]
fn unit_structs() {
// TODO: Instantiate a unit-like struct!
// let unit_like_struct =
let unit_like_struct = UnitLikeStruct;
let message = format!("{:?}s are fun!", unit_like_struct);
assert_eq!(message, "UnitLikeStructs are fun!");

View File

@ -2,8 +2,6 @@
// Address all the TODOs to make the tests pass!
// Execute `rustlings hint structs2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[derive(Debug)]
struct Order {
name: String,
@ -34,8 +32,15 @@ mod tests {
#[test]
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"),
year: order_template.year,
made_by_phone: order_template.made_by_phone,
made_by_mobile: order_template.made_by_mobile,
made_by_email: order_template.made_by_email,
item_number: order_template.item_number,
count: 1,
};
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!
// Execute `rustlings hint structs3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[derive(Debug)]
struct Package {
sender_country: String,
@ -26,12 +24,12 @@ impl Package {
}
}
fn is_international(&self) -> ??? {
// Something goes here...
fn is_international(&self) -> bool {
self.sender_country != self.recipient_country
}
fn get_fees(&self, cents_per_gram: i32) -> ??? {
// Something goes here...
fn get_fees(&self, cents_per_gram: i32) -> i32 {
return if cents_per_gram < 0 { 0 } else { self.weight_in_grams * cents_per_gram };
}
}

View File

@ -2,9 +2,7 @@
// Make me compile!
// Execute `rustlings hint variables1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
x = 5;
let x = 5;
println!("x has the value {}", x);
}

View File

@ -1,10 +1,8 @@
// variables2.rs
// Execute `rustlings hint variables2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
let x;
let x = 5;
if x == 10 {
println!("x is ten!");
} else {

View File

@ -1,9 +1,7 @@
// variables3.rs
// Execute `rustlings hint variables3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
let x: i32;
let x: i32 = 10;
println!("Number {}", x);
}

View File

@ -1,10 +1,8 @@
// variables4.rs
// Execute `rustlings hint variables4` or use the `hint` watch subcommand for 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,11 +1,9 @@
// variables5.rs
// Execute `rustlings hint variables5` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
let number = "T-H-R-E-E"; // don't change this line
println!("Spell a Number : {}", number);
number = 3; // don't rename this variable
let number = 3; // don't rename this variable
println!("Number plus two is : {}", number + 2);
}

View File

@ -1,9 +1,8 @@
// variables6.rs
// Execute `rustlings hint variables6` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
const NUMBER: i32 = 3;
const NUMBER = 3;
fn main() {
println!("Number {}", NUMBER);
}

View File

@ -4,11 +4,9 @@
// Make me compile and pass the test!
// Execute `rustlings hint vecs1` or use the `hint` watch subcommand for a hint.
// 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: Vec<i32> = vec![10, 20, 30, 40];
(a, v)
}

View File

@ -6,25 +6,16 @@
//
// Execute `rustlings hint vecs2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for element in v.iter_mut() {
// TODO: Fill this up so that each element in the Vec `v` is
// multiplied by 2.
???
*element = *element * 2;
}
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
v
}
fn vec_map(v: &Vec<i32>) -> Vec<i32> {
v.iter().map(|element| {
// TODO: Do the same thing as above - but instead of mutating the
// Vec, you can just return the new number!
???
}).collect()
v.iter().map(|element| { element * 2 }).collect()
}
#[cfg(test)]