Added chapter 6

This commit is contained in:
2020-06-11 16:01:20 -04:00
parent 744c3819a2
commit 3ecda72a85
5 changed files with 87 additions and 4 deletions

3
src/Conversion.rs Normal file
View File

@@ -0,0 +1,3 @@
pub mod FromAndInto;
pub mod TryFromAndTryInto;
pub mod ToAndFromStrings;

View File

@@ -0,0 +1,23 @@
#[derive(Debug)]
struct Number{
value: i32,
}
impl std::convert::From<i32> for Number{
fn from(item: i32) -> Self{
Number { value: item }
}
}
pub fn main(){
let num = Number::from(30);
println!("My number is {:?}", num);
let int = 5;
//Try removing the type declaration
let num: Number = int.into();
println!("My number is {:?}", num);
let my_str = "hello";
#[allow(unused_variables)]
let my_string = String::from(my_str);
}

View File

@@ -0,0 +1,20 @@
struct Circle{
radius: i32
}
impl std::fmt::Display for Circle{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result{
write!(f, "Circle of radius {}", self.radius)
}
}
pub fn main(){
let circle = Circle { radius: 6 };
println!("{}", circle.to_string());
let parsed: i32 = "5".parse().unwrap();
let turbo_parsed = "10".parse::<i32>().unwrap();
let sum = parsed + turbo_parsed;
println!("Sum: {:?}", sum);
}

View File

@@ -0,0 +1,28 @@
use std::convert::TryFrom;
use std::convert::TryInto;
#[derive(Debug, PartialEq)]
struct EvenNumber(i32);
impl std::convert::TryFrom<i32> for EvenNumber{
type Error = ();
fn try_from(value: i32) -> Result<Self, Self::Error>{
if value % 2 == 0 {
Ok(EvenNumber(value))
} else {
Err(())
}
}
}
pub fn main(){
//TryFrom
assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
assert_eq!(EvenNumber::try_from(5), Err(()));
//TryInto
let result: Result<EvenNumber, ()> = 8i32.try_into();
assert_eq!(result, Ok(EvenNumber(8)));
let result: Result<EvenNumber, ()> = 5i32.try_into();
assert_eq!(result, Err(()));
}

View File

@@ -6,6 +6,7 @@ mod Primitives;
mod CustomTypes; mod CustomTypes;
mod VariableBindings; mod VariableBindings;
mod Types; mod Types;
mod Conversion;
fn main(){ fn main(){
@@ -58,11 +59,19 @@ fn main(){
//5 Types //5 Types
//5.1 Casting //5.1 Casting
Types::Casting::main(); //Types::Casting::main();
//5.2 Literals //5.2 Literals
Types::Literals::main(); //Types::Literals::main();
//5.3 Inference //5.3 Inference
Types::Inference::main(); //Types::Inference::main();
//5.4 Aliasing //5.4 Aliasing
Types::Aliasing::main(); //Types::Aliasing::main();
//6 Conversion
//6.1 From and Into
Conversion::FromAndInto::main();
//6.2 TryFrom and TryInto
Conversion::TryFromAndTryInto::main();
//6.3 To and From Strings
Conversion::ToAndFromStrings::main();
} }