This commit is contained in:
Austin Jones 2022-01-19 16:26:28 -05:00
parent ffebb3c854
commit 9b1f6c3cb2
No known key found for this signature in database
GPG Key ID: 9DF9F702DA629FC3
16 changed files with 164 additions and 45 deletions

View File

@ -7,8 +7,6 @@
// Make this code compile! Execute `rustlings hint advanced_errs1` for
// hints :)
// I AM NOT DONE
use std::num::ParseIntError;
use std::str::FromStr;
@ -24,6 +22,15 @@ impl From<CreationError> for ParsePosNonzeroError {
fn from(e: CreationError) -> Self {
// TODO: complete this implementation so that the `?` operator will
// work for `CreationError`
ParsePosNonzeroError::Creation(e)
}
}
impl From<ParseIntError> for ParsePosNonzeroError {
fn from(e: ParseIntError) -> Self {
// TODO: complete this implementation so that the `?` operator will
// work for `CreationError`
ParsePosNonzeroError::ParseInt(e)
}
}

View File

@ -16,8 +16,6 @@
// 4. Complete the partial implementation of `Display` for
// `ParseClimateError`.
// I AM NOT DONE
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::num::{ParseFloatError, ParseIntError};
@ -47,11 +45,13 @@ impl From<ParseIntError> for ParseClimateError {
impl From<ParseFloatError> for ParseClimateError {
fn from(e: ParseFloatError) -> Self {
// TODO: Complete this function
Self::ParseFloat(e)
}
}
// TODO: Implement a missing trait so that `main()` below will compile. It
// is not necessary to implement any methods inside the missing trait.
impl Error for ParseClimateError {}
// The `Display` trait allows for other code to obtain the error formatted
// as a user-visible string.
@ -62,8 +62,11 @@ impl Display for ParseClimateError {
// Imports the variants to make the following code more compact.
use ParseClimateError::*;
match self {
Empty => write!(f, "empty input"),
NoCity => write!(f, "no city name"),
ParseInt(e) => write!(f, "error parsing year: {}", e),
ParseFloat(e) => write!(f, "error parsing temperature: {}", e),
Badlen => write!(f, "incorrect number of fields"),
_ => write!(f, "unhandled error!"),
}
}
@ -89,11 +92,21 @@ impl FromStr for Climate {
// TODO: Complete this function by making it handle the missing error
// cases.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let v: Vec<_> = s.split(',').collect();
if s.len() == 0 {
return Err(ParseClimateError::Empty);
}
let v: Vec<&str> = s.split(',').collect();
let (city, year, temp) = match &v[..] {
[city, year, temp] => (city.to_string(), year, temp),
_ => return Err(ParseClimateError::BadLen),
};
if city.len() == 0 {
return Err(ParseClimateError::NoCity);
}
let year: u32 = year.parse()?;
let temp: f32 = temp.parse()?;
Ok(Climate { city, year, temp })

View File

@ -6,8 +6,6 @@
// check clippy's suggestions from the output to solve the exercise.
// Execute `rustlings hint clippy1` for hints :)
// I AM NOT DONE
fn main() {
let x = 1.2331f64;
let y = 1.2332f64;

View File

@ -1,13 +1,13 @@
// clippy2.rs
// Make me compile! Execute `rustlings hint clippy2` for hints :)
// I AM NOT DONE
fn main() {
let mut res = 42;
let option = Some(12);
for x in option {
if let Some(x) = option {
res += x;
}
println!("{}", res);
}

View File

@ -4,11 +4,9 @@
// Make me compile and pass the test!
// Execute the command `rustlings hint vec1` if you need hints.
// 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![10, 20, 30, 40];// TODO: declare your vector here with the macro for vectors
(a, v)
}

View File

@ -7,12 +7,9 @@
// Execute the command `rustlings hint vec2` if you need
// hints.
// I AM NOT DONE
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for i in v.iter_mut() {
// TODO: Fill this up so that each element in the Vec `v` is
// multiplied by 2.
*i = *i * 2
}
// At this point, `v` should be equal to [4, 8, 12, 16, 20].

View File

@ -2,17 +2,15 @@
// Read more about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html
// and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively.
// I AM NOT DONE
// Obtain the number of bytes (not characters) in the given argument
// Add the AsRef trait appropriately as a trait bound
fn byte_counter<T>(arg: T) -> usize {
fn byte_counter<T: AsRef<str>>(arg: T) -> usize {
arg.as_ref().as_bytes().len()
}
// Obtain the number of characters (not bytes) in the given argument
// Add the AsRef trait appropriately as a trait bound
fn char_counter<T>(arg: T) -> usize {
fn char_counter<T: AsRef<str>>(arg: T) -> usize {
arg.as_ref().chars().count()
}

View File

@ -33,10 +33,33 @@ 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.len() == 0 {
return Person::default();
}
let mut s = s.split(",").collect::<Vec<&str>>();
if s.len() != 2 {
return Person::default();
}
let name = s[0].to_string();
if name.len() <= 0 {
return Person::default()
}
let age = match s[1].parse::<usize>() {
Ok(val) => val,
Err(_) => { return Person::default() },
};
Person {
name,
age,
}
}
}

View File

@ -26,8 +26,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
@ -41,6 +39,30 @@ enum ParsePersonError {
impl FromStr for Person {
type Err = ParsePersonError;
fn from_str(s: &str) -> Result<Person, Self::Err> {
if s.len() == 0 {
return Err(Self::Err::Empty);
}
let mut s = s.split(",").collect::<Vec<&str>>();
if s.len() != 2 {
return Err(Self::Err::BadLen);
}
let name = s[0].to_string();
if name.len() <= 0 {
return Err(Self::Err::NoName);
}
let age = match s[1].parse::<usize>() {
Ok(val) => val,
Err(err) => {
return Err(Self::Err::ParseInt(err));
}
};
Ok(Person { name, age })
}
}

View File

@ -21,8 +21,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,
@ -36,6 +34,25 @@ enum IntoColorError {
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
let red = if tuple.0 >= 0 && tuple.0 <= 255 {
tuple.0 as u8
} else {
return Err(Self::Error::IntConversion);
};
let green = if tuple.1 >= 0 && tuple.1 <= 255 {
tuple.1 as u8
} else {
return Err(Self::Error::IntConversion);
};
let blue = if tuple.2 >= 0 && tuple.2 <= 255 {
tuple.2 as u8
} else {
return Err(Self::Error::IntConversion);
};
Ok(Color { red, green, blue })
}
}
@ -43,6 +60,25 @@ 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 red = if arr[0] >= 0 && arr[0] <= 255 {
arr[0] as u8
} else {
return Err(Self::Error::IntConversion);
};
let green = if arr[1] >= 0 && arr[1] <= 255 {
arr[1] as u8
} else {
return Err(Self::Error::IntConversion);
};
let blue = if arr[2] >= 0 && arr[2] <= 255 {
arr[2] as u8
} else {
return Err(Self::Error::IntConversion);
};
Ok(Color { red, green, blue })
}
}
@ -50,6 +86,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(Self::Error::BadLen);
}
let red = if slice[0] >= 0 && slice[0] <= 255 {
slice[0] as u8
} else {
return Err(Self::Error::IntConversion);
};
let green = if slice[1] >= 0 && slice[1] <= 255 {
slice[1] as u8
} else {
return Err(Self::Error::IntConversion);
};
let blue = if slice[2] >= 0 && slice[2] <= 255 {
slice[2] as u8
} else {
return Err(Self::Error::IntConversion);
};
Ok(Color { red, green, blue })
}
}

View File

@ -5,11 +5,9 @@
// The goal is to make sure that the division does not fail to compile
// and returns the proper type.
// I AM NOT DONE
fn average(values: &[f64]) -> f64 {
let total = values.iter().fold(0.0, |a, b| a + b);
total / values.len()
total / values.len() as f64
}
fn main() {

View File

@ -1,8 +1,6 @@
// macros1.rs
// Make me compile! Execute `rustlings hint macros1` for hints :)
// I AM NOT DONE
macro_rules! my_macro {
() => {
println!("Check out my macro!");
@ -10,5 +8,5 @@ macro_rules! my_macro {
}
fn main() {
my_macro();
my_macro!();
}

View File

@ -1,14 +1,13 @@
// macros2.rs
// Make me compile! Execute `rustlings hint macros2` for hints :)
// I AM NOT DONE
fn main() {
my_macro!();
}
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
fn main() {
my_macro!();
}

View File

@ -2,14 +2,15 @@
// Make me compile, without taking the macro out of the module!
// Execute `rustlings hint macros3` for hints :)
// I AM NOT DONE
mod macros {
#[macro_export]
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
pub(crate) use my_macro;
}
fn main() {

View File

@ -1,12 +1,10 @@
// macros4.rs
// Make me compile! Execute `rustlings hint macros4` for hints :)
// I AM NOT DONE
macro_rules! my_macro {
() => {
println!("Check out my macro!");
}
};
($val:expr) => {
println!("Look at this other macro: {}", $val);
}

View File

@ -5,7 +5,16 @@
// Write a macro that passes the quiz! No hints this time, you can do it!
// I AM NOT DONE
mod macros {
#[macro_export]
macro_rules! my_macro {
($val:expr) => {
format!("Hello {}", $val)
};
}
pub(crate) use my_macro;
}
#[cfg(test)]
mod tests {