complete session1 exercises.

This commit is contained in:
dbqls9713 2022-10-28 19:57:54 +09:00
parent b17295b36f
commit b388202210
39 changed files with 107 additions and 66 deletions

View File

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

View File

@ -6,6 +6,10 @@
#[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 {

View File

@ -6,6 +6,10 @@
enum Message {
// TODO: implement the message variant types based on their usage below
ChangeColor((u8, u8, u8)),
Echo(String),
Move(Point),
Quit
}
struct Point {
@ -38,6 +42,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_tup) => self.change_color(color_tup),
Message::Echo(string) => self.echo(string),
Message::Move(pos) => self.move_position(pos),
Message::Quit => self.quit()
}
}
}

View File

@ -7,12 +7,12 @@
// 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))
}
}

View File

@ -25,8 +25,10 @@ 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)]

View File

@ -8,7 +8,7 @@
use std::num::ParseIntError;
fn main() {
fn main()-> Result<(), ParseIntError>{
let mut tokens = 100;
let pretend_user_input = "8";
@ -20,6 +20,7 @@ fn main() {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
Ok(())
}
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {

View File

@ -15,6 +15,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))
}
}

View File

@ -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)?);

View File

@ -25,6 +25,9 @@ impl ParsePosNonzeroError {
}
// 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)
@ -32,7 +35,7 @@ fn parse_pos_nonzero(s: &str)
{
// 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)
}

View File

@ -3,6 +3,9 @@
// I AM NOT DONE
fn call_me() {
print!("hello world!");
}
fn main() {
call_me();
}

View File

@ -7,7 +7,7 @@ fn main() {
call_me(3);
}
fn call_me(num:) {
fn call_me(num:u32) {
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(5);
}
fn call_me(num: u32) {

View File

@ -14,7 +14,7 @@ fn main() {
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

@ -9,5 +9,5 @@ fn main() {
}
fn square(num: i32) -> i32 {
num * num;
num * num
}

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

@ -5,5 +5,5 @@
// I AM NOT DONE
fn main() {
println!("Hello {}!");
println!("Hello {}!","world");
}

View File

@ -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);

View File

@ -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);
@ -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);

View File

@ -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);

View File

@ -7,9 +7,7 @@
// 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 +18,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

@ -8,8 +8,8 @@
fn main() {
let mut x = 100;
let y = &mut x;
let z = &mut x;
*y += 100;
let z = &mut x;
*z += 1000;
assert_eq!(x, 1200);
}

View File

@ -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);
}

View File

@ -26,11 +26,11 @@ use std::thread;
fn main() {
let numbers: Vec<_> = (0..100u32).collect();
let shared_numbers = // TODO
let shared_numbers = Arc::new(numbers); // TODO
let mut joinhandles = Vec::new();
for offset in 0..8 {
let child_numbers = // TODO
let child_numbers = shared_numbers.clone();// TODO
joinhandles.push(thread::spawn(move || {
let sum: u32 = child_numbers.iter().filter(|n| *n % 8 == offset).sum();
println!("Sum of offset {} is {}", offset, sum);

View File

@ -9,6 +9,6 @@ fn main() {
println!("My current favorite color is {}", answer);
}
fn current_favorite_color() -> String {
fn current_favorite_color() -> &'static str {
"blue"
}

View File

@ -13,6 +13,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"
}

View File

@ -5,17 +5,17 @@
fn trim_me(input: &str) -> String {
// TODO: Remove whitespace from both ends of a string!
???
input.to_string().trim().to_string()
}
fn compose_me(input: &str) -> String {
// TODO: Add " world!" to the string! There's multiple ways to do this!
???
input.to_string() + " world!"
}
fn replace_me(input: &str) -> String {
// TODO: Replace "cars" in the string with "balloons"!
???
input.to_string().replace("cars", "balloons")
}
#[cfg(test)]

View File

@ -16,14 +16,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());
}

View File

@ -6,9 +6,12 @@
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;
@ -20,7 +23,11 @@ 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);
@ -30,7 +37,8 @@ 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);
@ -40,7 +48,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

@ -35,7 +35,12 @@ mod tests {
fn your_order() {
let order_template = create_order_template();
// TODO: Create your own order using the update syntax and template above!
// let your_order =
let your_order = Order {
name : String::from("Hacker in Rust"),
count : 1,
..order_template
};
assert_eq!(your_order.name, "Hacker in Rust");
assert_eq!(your_order.year, order_template.year);
assert_eq!(your_order.made_by_phone, order_template.made_by_phone);

View File

@ -26,12 +26,14 @@ impl Package {
}
}
fn is_international(&self) -> ??? {
fn is_international(&self) -> bool {
// Something goes here...
self.sender_country != self.recipient_country
}
fn get_fees(&self, cents_per_gram: i32) -> ??? {
fn get_fees(&self, cents_per_gram: i32) -> i32{
// Something goes here...
self.weight_in_grams * cents_per_gram
}
}

View File

@ -13,6 +13,6 @@
mod tests {
#[test]
fn you_can_assert() {
assert!();
assert!(true);
}
}

View File

@ -9,6 +9,6 @@
mod tests {
#[test]
fn you_can_assert_eq() {
assert_eq!();
assert_eq!(true, false);
}
}

View File

@ -16,11 +16,11 @@ mod tests {
#[test]
fn is_true_when_even() {
assert!();
assert!(is_even(4));
}
#[test]
fn is_false_when_odd() {
assert!();
assert!(!is_even(5));
}
}

View File

@ -5,6 +5,6 @@
// I AM NOT DONE
fn main() {
x = 5;
let x = 5;
println!("x has the value {}", x);
}

View File

@ -4,7 +4,7 @@
// I AM NOT DONE
fn main() {
let x;
let x = 10;
if x == 10 {
println!("x is ten!");
} else {

View File

@ -4,6 +4,6 @@
// I AM NOT DONE
fn main() {
let x: i32;
let x: i32 = 0;
println!("Number {}", x);
}

View File

@ -4,7 +4,7 @@
// 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

@ -6,6 +6,6 @@
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

@ -3,7 +3,7 @@
// I AM NOT DONE
const NUMBER = 3;
const NUMBER:u32 = 3;
fn main() {
println!("Number {}", NUMBER);
}