Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions exercises/enums/enums1.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// enums1.rs
// No hints this time! ;)

// I AM NOT DONE

#[derive(Debug)]
enum Message {
// TODO: define a few types of messages as used below
Quit,
Echo,
Move,
ChangeColor
}

fn main() {
Expand Down
6 changes: 4 additions & 2 deletions exercises/enums/enums2.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// 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: i32, y: i32},
Echo(String),
ChangeColor(i32, i32, i32),
Quit
}

impl Message {
Expand Down
13 changes: 10 additions & 3 deletions exercises/enums/enums3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
// 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 {
Expand Down Expand Up @@ -37,7 +39,12 @@ impl State {
}

fn process(&mut self, message: Message) {
// TODO: create a match expression to process the different message variants
match message {
Message::ChangeColor(color) => self.change_color(color),
Message::Echo(string) => self.echo(string),
Message::Move(position) => self.move_position(position),
Message::Quit => self.quit()
}
}
}

Expand Down
9 changes: 4 additions & 5 deletions exercises/error_handling/errors1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@
// construct to `Option` that can be used to express error conditions. Let's use it!
// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a hint.

// 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.is_empty() {
// Empty names aren't allowed.
None
Err("`name` was empty; it must be nonempty.".into())
} else {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
}
}

Expand Down
9 changes: 5 additions & 4 deletions exercises/error_handling/errors2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,17 @@
// one is a lot shorter!
// Execute `rustlings hint errors2` or use the `hint` watch subcommand for a hint.

// 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>();

Ok(qty * cost_per_item + processing_fee)
match qty
{
Ok(value) => Ok(value * cost_per_item + processing_fee), _ => qty
}

}

#[cfg(test)]
Expand Down
5 changes: 2 additions & 3 deletions exercises/error_handling/errors3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

use std::num::ParseIntError;

fn main() {
fn main() -> Result<(), ParseIntError> {
let mut tokens = 100;
let pretend_user_input = "8";

Expand All @@ -20,6 +18,7 @@ fn main() {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
Ok(())
}

pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
Expand Down
7 changes: 5 additions & 2 deletions exercises/error_handling/errors4.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// errors4.rs
// Execute `rustlings hint errors4` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
Expand All @@ -14,7 +13,11 @@ enum CreationError {

impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
// Hmm...? Why is this only returning an Ok value?
if value < 0 {
return Err(CreationError::Negative)
} else if value == 0 {
return Err(CreationError::Zero)
}
Ok(PositiveNonzeroInteger(value as u64))
}
}
Expand Down
2 changes: 1 addition & 1 deletion exercises/error_handling/errors5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use std::fmt;
use std::num::ParseIntError;

// TODO: update the return type of `main()` to make this compile.
fn main() -> Result<(), Box<dyn ???>> {
fn main() -> Result<(), Box<dyn error::Error>> {
let pretend_user_input = "42";
let x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
Expand Down
10 changes: 5 additions & 5 deletions exercises/error_handling/errors6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ impl ParsePosNonzeroError {
fn from_creation(err: CreationError) -> ParsePosNonzeroError {
ParsePosNonzeroError::Creation(err)
}
// TODO: add another error conversion function here.
// fn from_parseint...

fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError {
ParsePosNonzeroError::ParseInt(err)
}
}

fn parse_pos_nonzero(s: &str)
-> Result<PositiveNonzeroInteger, ParsePosNonzeroError>
{
// TODO: change this to return an appropriate error instead of panicking
// when `parse()` returns an error.
let x: i64 = s.parse().unwrap();
let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parseint)?;
PositiveNonzeroInteger::new(x)
.map_err(ParsePosNonzeroError::from_creation)
}
Expand Down
5 changes: 2 additions & 3 deletions exercises/intro/intro2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
// 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 {}!");
let greeting = "World";
println!("Hello {}!", greeting);
}
2 changes: 1 addition & 1 deletion exercises/move_semantics/move_semantics1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
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);

Expand Down
6 changes: 3 additions & 3 deletions exercises/move_semantics/move_semantics2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
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);
Expand All @@ -17,8 +17,8 @@ fn main() {
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.to_vec();

vec.push(22);
vec.push(44);
Expand Down
2 changes: 1 addition & 1 deletion exercises/move_semantics/move_semantics3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,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);
Expand Down
5 changes: 2 additions & 3 deletions exercises/move_semantics/move_semantics4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@
// 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);

Expand All @@ -20,7 +19,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);
Expand Down
3 changes: 2 additions & 1 deletion exercises/move_semantics/move_semantics5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
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);
}
10 changes: 5 additions & 5 deletions exercises/move_semantics/move_semantics6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@
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: &str) -> 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);
}
5 changes: 2 additions & 3 deletions exercises/standard_library_types/arc1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,18 @@
// where the second TODO comment is. Try not to create any copies of the `numbers` Vec!
// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

#![forbid(unused_imports)] // Do not change this, (or the next) line.
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 = // TODO
let child_numbers = shared_numbers.clone();
joinhandles.push(thread::spawn(move || {
let sum: u32 = child_numbers.iter().filter(|n| *n % 8 == offset).sum();
println!("Sum of offset {} is {}", offset, sum);
Expand Down
4 changes: 1 addition & 3 deletions exercises/strings/strings1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
return "blue".to_string();
}
4 changes: 1 addition & 3 deletions exercises/strings/strings2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
// 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) {
Expand All @@ -13,6 +11,6 @@ fn main() {
}
}

fn is_a_color_word(attempt: &str) -> bool {
fn is_a_color_word(attempt: String) -> bool {
attempt == "green" || attempt == "blue" || attempt == "red"
}
13 changes: 4 additions & 9 deletions exercises/strings/strings3.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
// 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!
???
return input.trim().to_string();
}

fn compose_me(input: &str) -> String {
// TODO: Add " world!" to the string! There's multiple ways to do this!
???
fn compose_me(input: &str) -> String {
return input.to_string() + " world!";
}

fn replace_me(input: &str) -> String {
// TODO: Replace "cars" in the string with "balloons"!
???
return input.replace("cars", "balloons");
}

#[cfg(test)]
Expand Down
22 changes: 10 additions & 12 deletions exercises/strings/strings4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
// 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);
}
Expand All @@ -16,14 +14,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_slice("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());
}
Loading