fix: ✏️ typos and compiler warnings

This commit is contained in:
Ahmet Kaan GÜMÜŞ 2024-06-17 18:19:36 +03:00
parent 82c2fb8883
commit 528969944d
17 changed files with 578 additions and 632 deletions

View file

@ -1,38 +1,31 @@
//Libs //Libs
use std::io;
use std::cmp::Ordering;
use rand::Rng; use rand::Rng;
//Funcs use std::cmp::Ordering;
fn main() use std::io;
{ //Functions
fn main() {
println!("Hello, world!\n"); println!("Hello, world!\n");
let secret_number = rand::thread_rng().gen_range(1..=10); let secret_number = rand::thread_rng().gen_range(1..=10);
println!("\t--> Guessing Game <--"); println!("\t--> Guessing Game <--");
println!("Secret Number = {secret_number}"); println!("Secret Number = {secret_number}");
loop loop {
{
println!("Give a guess ↓ "); println!("Give a guess ↓ ");
let mut guess = String::new(); let mut guess = String::new();
io::stdin() io::stdin()
.read_line(&mut guess) .read_line(&mut guess)
.expect("Failed to read line"); .expect("Failed to read line");
let guess: u32 = match let guess: u32 = match guess.trim().parse() {
guess.trim()
.parse()
{
Ok(num) => num, Ok(num) => num,
Err(_) => continue, Err(_) => continue,
}; };
println!("You Guessed = {guess}"); println!("You Guessed = {guess}");
match guess.cmp(&secret_number) match guess.cmp(&secret_number) {
{
Ordering::Less => println!("Too small"), Ordering::Less => println!("Too small"),
Ordering::Greater => println!("Too big"), Ordering::Greater => println!("Too big"),
Ordering::Equal => Ordering::Equal => {
{
println!("You win"); println!("You win");
break; break;
} }
} }
} }
} }

View file

@ -2,33 +2,33 @@ fn main() {
println!("Hello, world!"); println!("Hello, world!");
//Integer //Integer
let a:i8 = 127; //(2^7-1) let a: i8 = 127; //(2^7-1)
let au:u8 = 255; //(2^8-1) let au: u8 = 255; //(2^8-1)
println!("a={a}\nau={au}"); println!("a={a}\nau={au}");
let b:i16 = 32767; //(2^15-1) let b: i16 = 32767; //(2^15-1)
let bu:u16 = 65535; //(2^16-1) let bu: u16 = 65535; //(2^16-1)
println!("b={b}\nbu={bu}"); println!("b={b}\nbu={bu}");
let c:i32 = 2147483647; //(2^31-1) let c: i32 = 2147483647; //(2^31-1)
let cu:u32 = 4294967295; //(2^32-1) let cu: u32 = 4294967295; //(2^32-1)
println!("c={c}\ncu={cu}"); println!("c={c}\ncu={cu}");
let d:i64 = 9223372036854775807; //(2^63-1) let d: i64 = 9223372036854775807; //(2^63-1)
let du:u64 = 18446744073709551615; //(2^64-1) let du: u64 = 18446744073709551615; //(2^64-1)
println!("d={d}\ndu={du}"); println!("d={d}\ndu={du}");
let e:i128 = 170141183460469231731687303715884105727; //(2^127-1) let e: i128 = 170141183460469231731687303715884105727; //(2^127-1)
let eu:u128 = 340282366920938463463374607431768211455; //(2^128-1) let eu: u128 = 340282366920938463463374607431768211455; //(2^128-1)
println!("e={e}\neu={eu}"); println!("e={e}\neu={eu}");
let f:isize = d as isize; //Based on Architechture of CPU = i64 for me let f: isize = d as isize; //Based on Architecture of CPU = i64 for me
let fu:usize = du as usize; //Also Explicit Conversion let fu: usize = du as usize; //Also Explicit Conversion
println!("f={f}\nfu={fu}"); println!("f={f}\nfu={fu}");
//Float //Float
let g:f32 = 0.123456789123456789; //7-precision I think let g: f32 = 0.123456789123456789; //7-precision I think
let h:f64 = 0.123456789123456789; //17-precision I think let h: f64 = 0.123456789123456789; //17-precision I think
println!("g={g}\nh={h}"); println!("g={g}\nh={h}");
//Boolean //Boolean
@ -42,19 +42,25 @@ fn main() {
println!("k={k}\nl={l}"); println!("k={k}\nl={l}");
//Tuple //Tuple
let tup = ("Tahinli",13,3.14); let tup = ("Tahinli", 13, 3.14);
println!("Tuple = {}-{}-{}", tup.0, tup.1, tup.2); println!("Tuple = {}-{}-{}", tup.0, tup.1, tup.2);
let (x,y,z) = tup; //Destructuring let (x, y, z) = tup; //Destructuring
println!("X-Y-Z = {x}-{y}-{z}"); println!("X-Y-Z = {x}-{y}-{z}");
//Array //Array
let ar = [0,1,2,3,4]; let array_1 = [0, 1, 2, 3, 4];
//I havent learn finite loop in Rust sorry. //I haven't learn finite loop in Rust sorry.
println!("ar[0]={}\nar[1]={}\nar[2]={}\nar[3]={}\nar[4]={}",ar[0], ar[1], ar[2], ar[3], ar[4]); println!(
"array_1[0]={}\narray_1[1]={}\narray_1[2]={}\narray_1[3]={}\narray_1[4]={}",
array_1[0], array_1[1], array_1[2], array_1[3], array_1[4]
);
let arr = [13;5]; let array_2 = [13; 5];
println!("arr[0]={}\narr[1]={}\narr[2]={}\narr[3]={}\narr[4]={}",arr[0], arr[1], arr[2], arr[3], arr[4]); println!(
"array_2[0]={}\narray_2[1]={}\narray_2[2]={}\narray_2[3]={}\narray_2[4]={}",
array_2[0], array_2[1], array_2[2], array_2[3], array_2[4]
);
let arrr : [f64;2] = [0.1,2.3]; let array_3: [f64; 2] = [0.1, 2.3];
println!("arrr[0]={}\narrr[1]={}", arrr[0], arrr[1]); println!("array_3[0]={}\narray_3[1]={}", array_3[0], array_3[1]);
} }

View file

@ -1,26 +1,22 @@
fn main() fn main() {
{
hello(); hello();
let x = { let x = {
let y = 5; //Statement let y = 5; //Statement
y+0 //Expression y + 0 //Expression
}; };
println!("X = {}", x); println!("X = {}", x);
let y = return_value(x); let y = return_value(x);
println!("Y = {}", y) println!("Y = {}", y)
} }
fn hello() fn hello() {
{
println!("Hello World"); println!("Hello World");
} }
fn return_value(mut x:i32) -> i32 fn return_value(mut x: i32) -> i32 {
{
println!("We're going to return something"); println!("We're going to return something");
x = x+1; x = x + 1;
x*x x * x
} }

View file

@ -3,55 +3,46 @@ fn main() {
let x = 3; let x = 3;
if x<0 if x < 0 {
{
println!("Below Zero"); println!("Below Zero");
} } else if x == 0 {
else if x==0
{
println!("Equals Zero"); println!("Equals Zero");
} } else {
else
{
println!("Above Zero"); println!("Above Zero");
} }
let val = true; let val = true;
let x = if val {5} else {7}; let x = if val { 5 } else { 7 };
println!("X is = {x}"); println!("X is = {x}");
'outer_loop: loop //Labeling a loop 'outer_loop: loop
//Labeling a loop
{ {
println!("Outer Loop"); println!("Outer Loop");
'inner_loop: loop 'inner_loop: loop {
{
println!("Inner Loop"); println!("Inner Loop");
if x==5 if x == 5 {
{
break 'outer_loop; break 'outer_loop;
} } else {
else
{
break 'inner_loop; break 'inner_loop;
} }
} }
} }
let mut y = 0; let mut y = 0;
while y==0 while y == 0 {
{
y += 1; y += 1;
} }
let q = [0,1,2,3,4]; let q = [0, 1, 2, 3, 4];
for element in q //For Each for element in q
//For Each
{ {
println!("Element of Array = {element}"); println!("Element of Array = {element}");
} }
for element in (0..100).rev() //Standart For for element in (0..100).rev()
//Standard For
{ {
println!("Element = {element}"); println!("Element = {element}");
} }
} }

View file

@ -1,52 +1,45 @@
use std::io; use std::io;
fn get_input() -> i32 fn get_input() -> i32 {
{ loop {
loop
{
let mut input = String::new(); let mut input = String::new();
io::stdin() io::stdin()
.read_line(&mut input) .read_line(&mut input)
.expect("Failed to read line"); .expect("Failed to read line");
match input.trim().parse() match input.trim().parse() {
{
Ok(num) => return num, Ok(num) => return num,
Err(_) => Err(_) => {
{
println!("Expected Valid Number"); println!("Expected Valid Number");
} }
}; };
} }
} }
fn main() fn main() {
{
println!("Hello, world!"); println!("Hello, world!");
println!("1) Fahrenheit to Celsius\n2) Celsius to Fahrenheit"); println!("1) Fahrenheit to Celsius\n2) Celsius to Fahrenheit");
let mut selection; let mut selection;
let mut b = true; let mut b = true;
while b while b {
{
selection = get_input(); selection = get_input();
match selection match selection {
{ 1 => {
1 =>
{
println!("Fahrenheit Value = ↓"); println!("Fahrenheit Value = ↓");
selection = get_input(); selection = get_input();
println!("Celsius Value = {}", (selection-32) as f32*5.0/9.0); println!("Celsius Value = {}", (selection - 32) as f32 * 5.0 / 9.0);
b = false; b = false;
}, }
2 => 2 => {
{
println!("Celsius Value = ↓"); println!("Celsius Value = ↓");
selection = get_input(); selection = get_input();
println!("Fahrenheit Value = {}", (selection as f32*9.0/5.0)+32.0); println!(
"Fahrenheit Value = {}",
(selection as f32 * 9.0 / 5.0) + 32.0
);
b = false; b = false;
}, }
_ => _ => {
{
println!("Expected Valid Value"); println!("Expected Valid Value");
},
} }
} }
} }
}

View file

@ -1,38 +1,31 @@
use std::io; use std::io;
fn get_input()->u32 fn get_input() -> u32 {
{ loop {
loop
{
let mut input = String::new(); let mut input = String::new();
io::stdin() io::stdin()
.read_line(&mut input) .read_line(&mut input)
.expect("Failed to read line"); .expect("Failed to read line");
match input.trim().parse() match input.trim().parse() {
{
Ok(num) => return num, Ok(num) => return num,
Err(_) => Err(_) => {
{
println!("Expected Valid Number"); println!("Expected Valid Number");
} }
}; };
} }
} }
fn fibo(val:u32)->u128 fn fibonacci(val: u32) -> u128 {
{
let mut a = 0; let mut a = 0;
let mut b = 1; let mut b = 1;
let mut c; let mut c;
for _element in 2..=val for _element in 2..=val {
{ c = a + b;
c = a+b;
a = b; a = b;
b = c; b = c;
} }
return b; return b;
} }
fn main() fn main() {
{
println!("Hello, world!"); println!("Hello, world!");
println!("Give a Number for Fibonacci Calculation ↓"); println!("Give a Number for Fibonacci Calculation ↓");
println!("Result = {}",fibo(get_input())); println!("Result = {}", fibonacci(get_input()));
} }

View file

@ -1,65 +1,49 @@
use std::io; use std::io;
fn get_input()->u32 fn get_input() -> u32 {
{ loop {
loop
{
let mut input = String::new(); let mut input = String::new();
io::stdin() io::stdin()
.read_line(&mut input) .read_line(&mut input)
.expect("Failed to read line"); .expect("Failed to read line");
match input.trim().parse() match input.trim().parse() {
{
Ok(num) => return num, Ok(num) => return num,
Err(_) => Err(_) => {
{
println!("Expected Valid Number"); println!("Expected Valid Number");
} }
}; };
} }
} }
fn prime(limit:u32)->i8 fn prime(limit: u32) -> i8 {
{ if limit < 2 {
if limit < 2
{
println!("None"); println!("None");
return -1; return -1;
} }
println!("\t2"); println!("\t2");
if limit == 2 if limit == 2 {
{
return 0; return 0;
} }
let mut b; let mut b;
for i in (3..=limit).step_by(2) for i in (3..=limit).step_by(2) {
{
b = true; b = true;
if i%2 != 0 if i % 2 != 0 {
{ for j in (3..=(i as f64).sqrt() as u32).step_by(2) {
for j in (3..=(i as f64).sqrt()as u32).step_by(2) if i % j == 0 {
{
if i%j == 0
{
//println!("{} is even", i); //println!("{} is even", i);
b = false; b = false;
break; break;
} }
} }
if b == true if b == true {
{
println!("\t{}", i); println!("\t{}", i);
} }
} }
} }
return 0; return 0;
} }
fn main() fn main() {
{
println!("Hello, world!"); println!("Hello, world!");
println!("Limit for Prime = ↓"); println!("Limit for Prime = ↓");
prime(get_input()); prime(get_input());
}
}

View file

@ -1,9 +1,7 @@
fn main() fn main() {
{
println!("Hello, world!"); println!("Hello, world!");
//Keeps data itself in heap for strings
//Keeps data in heap
//Information about data are in stack //Information about data are in stack
//Because data can be changed in runtime //Because data can be changed in runtime
@ -25,4 +23,4 @@ fn main()
let y = x; let y = x;
println!("x = {}", x); println!("x = {}", x);
println!("y = {}", y); println!("y = {}", y);
} }

View file

@ -1,10 +1,9 @@
fn main() fn main() {
{
println!("Hello, world!"); println!("Hello, world!");
let n = 5; let n = 5;
let s1 = String::from("Learning Ownership"); let s1 = String::from("Learning Ownership");
take_ownership(s1, n);//s1 is moved n is copied take_ownership(s1, n); //s1 is moved n is copied
//println!("{}", s1); It's gone //println!("{}", s1); It's gone
println!("Not Transferred, Just Copied = {}", n); println!("Not Transferred, Just Copied = {}", n);
@ -12,18 +11,15 @@ fn main()
let s3 = take_then_give_back_ownership(s2); let s3 = take_then_give_back_ownership(s2);
//println!("s2 = {}", s2); s2 is long gone //println!("s2 = {}", s2); s2 is long gone
println!("s3 = {}", s3); println!("s3 = {}", s3);
}
} fn take_ownership(our_string: String, our_number: i32) {
fn take_ownership(our_string:String, our_number:i32)
{
//ownership is transferred for string //ownership is transferred for string
println!("I got your String = {}", our_string); println!("I got your String = {}", our_string);
println!("I got your Number = {}", our_number); println!("I got your Number = {}", our_number);
} //calls "drop" for string, so our_string is gone now } //calls "drop" for string, so our_string is gone now
fn take_then_give_back_ownership(our_string:String) -> String fn take_then_give_back_ownership(our_string: String) -> String {
{
println!("Now String is Here = {}", our_string); println!("Now String is Here = {}", our_string);
our_string our_string
} }

View file

@ -1,12 +1,11 @@
fn main() fn main() {
{
println!("Hello, world!"); println!("Hello, world!");
//We can not have another reference, if we have a mutable one //We can not have another reference, if we have a mutable one
let mut s1 = String::from("Safe"); let mut s1 = String::from("Safe");
let r1 = &s1; let r1 = &s1;
let r2 = &s1; let r2 = &s1;
//If an unmutable reference will be used, we can not have mutable one //If an immutable reference will be used, we can not have mutable one
//let r3 = &mut s2; //let r3 = &mut s2;
//println!("References = {}-{}-{}", r1, r2, r3); //println!("References = {}-{}-{}", r1, r2, r3);
println!("References = {}-{}", r1, r2); println!("References = {}-{}", r1, r2);
@ -16,30 +15,28 @@ fn main()
//let r4 = &mut s2; //let r4 = &mut s2;
//println!("New References = {}-{}", r3, r4); //println!("New References = {}-{}", r3, r4);
println!("New Mutable Reference = {}", r3); println!("New Mutable Reference = {}", r3);
//r3 isn't going to use anymore, we are free again to have another mutable reference //r3 isn't going to use any longer, we are free again to have another mutable reference
let r4 = &mut s1; let r4 = &mut s1;
println!("New Mutable Reference Again = {}", r4); println!("New Mutable Reference Again = {}", r4);
let mut s2 = String::from("Traveler"); let mut s2 = String::from("Traveller");
//No need to copy same values, or return anything //No need to copy same values, or return anything
//Because we do not give owenership, just borrowing //Because we do not give ownership, just borrowing
borrow1(&s2); borrow1(&s2);
borrow2(&mut s2); borrow2(&mut s2);
println!("s2 = {}", s2); println!("s2 = {}", s2);
//Because of unallocation after scope, this reference would be refered unallocated place //Because of deallocation after scope, this reference would be referred unallocated place
//Rust checks this, while compling to save us from runtime error //Rust checks this, while compiling to save us from runtime error
//let dangle_reference = dangling(); //let dangle_reference = dangling();
} }
fn borrow1(string_reference : &String) fn borrow1(string_reference: &String) {
{
println!("Length of String is = {}", string_reference.len()); println!("Length of String is = {}", string_reference.len());
} }
fn borrow2(string_reference : &mut String) fn borrow2(string_reference: &mut String) {
{
string_reference.push_str(" Code"); string_reference.push_str(" Code");
} }
/*fn dangling() -> &String /*fn dangling() -> &String
{ {
let mut some_string = String::from("Are we dangle ?"); let mut some_string = String::from("Are we dangle ?");
&some_string &some_string
}*/ }*/

View file

@ -1,42 +1,38 @@
fn main() fn main() {
{
println!("Hello, world!"); println!("Hello, world!");
//mutable because we will clean it later. //mutable because we will clean it later.
let mut s = String::from("Yellow Duck"); let mut s = String::from("Yellow Duck");
//it's not &String, it's literal reference thanks to slice //it's not &String, it's literal reference thanks to slice
let firts = firts_world(&s[..]); let first = first_world(&s[..]);
println!("{}", firts); println!("{}", first);
s.clear(); s.clear();
//s.clear function has mutable reference to truncate //s.clear function has mutable reference to truncate
//and if we print "first" after this //and if we print "first" after this
//we have to have mutable and immutable references //we have to have mutable and immutable references
//at the same time //at the same time
//it's forbidden as we've learned before //it's forbidden as we've learned before
//println!("{}", firts); //println!("{}", first);
let a = [0,1,2,3,4,5]; let a = [0, 1, 2, 3, 4, 5];
let b = &a[2..4]; let b = &a[2..4];
println!("{}-{}", b[0], b[1]); println!("{}-{}", b[0], b[1]);
} }
fn firts_world(s: &str) -> &str fn first_world(s: &str) -> &str {
{
//it converts string to byte array //it converts string to byte array
let bytes = s.as_bytes(); let bytes = s.as_bytes();
//iter is iteration we will learn later, even i don't know well //iter is iteration we will learn later, even i don't know well
//enumerate returns index and reference in order as a tuple //enumerate returns index and reference in order as a tuple
for(i, &item) in bytes.iter().enumerate() for (i, &item) in bytes.iter().enumerate() {
{ //We're trying to catch "space" to separate our string
//We're trying to catch "space" to sepeterate our string
//Book says also we will learn pattern matching later //Book says also we will learn pattern matching later
if item == b' ' if item == b' ' {
{
//when we find "space", we return first slice //when we find "space", we return first slice
return &s[0..i]; return &s[0..i];
} }
} }
//If we can not find any space, we return whole string as a literal //If we can not find any space, we return whole string as a literal
&s[..] &s[..]
} }

View file

@ -1,65 +1,73 @@
//this is how we implement struct //this is how we implement struct
struct Person struct Person {
{
id: u8, id: u8,
tel: u8, tel: u8,
name: String, name: String,
alive: bool, alive: bool,
} }
//they're tuple struct //they're tuple struct
//they might seem like same but different //they might seem like same but different
struct RGB(u8,u8,u8); struct RGB(u8, u8, u8);
struct Coordinates(u8,u8,u8); struct Coordinates(u8, u8, u8);
//this is unit-like struct //this is unit-like struct
//i don't know what to do now, but seems like it's about "trait" //i don't know what to do now, but seems like it's about "trait"
struct UnitLike; struct UnitLike;
fn add_person(id:u8, tel:u8, name:String, alive:bool) ->Person fn add_person(id: u8, tel: u8, name: String, alive: bool) -> Person {
{ //if struct variables and function variables has same name
//if struct variables and funciton variables has same name
//no need to specify again //no need to specify again
Person { id, tel, name, alive } Person {
id,
tel,
name,
alive,
} }
fn main() }
{ fn main() {
println!("Hello, world!"); println!("Hello, world!");
let mut person1 = Person let mut person1 = Person {
{ id: 101,
id : 101, tel: 111,
tel : 111, name: String::from("Ahmet"),
name : String::from("Ahmet"), alive: false,
alive : false,
}; };
person1.name = String::from(person1.name+" Kaan"); person1.name = String::from(person1.name + " Kaan");
println!("{}\n{}\n{}\n{}", person1.id, person1.tel, person1.name, person1.alive); println!(
"{}\n{}\n{}\n{}",
person1.id, person1.tel, person1.name, person1.alive
);
let person2 = Person let person2 = Person {
{ tel: 112,
tel : 112,
..person1 ..person1
}; };
//person.name is going to be problem. because it's moved already //person.name is going to be problem. because it's moved already
//println!("{}\n{}\n{}\n{}", person1.id, person1.tel, person1.name, person1.alive); //println!("{}\n{}\n{}\n{}", person1.id, person1.tel, person1.name, person1.alive);
println!("{}\n{}\n{}\n{}", person2.id, person2.tel, person2.name, person2.alive); println!(
"{}\n{}\n{}\n{}",
person2.id, person2.tel, person2.name, person2.alive
);
//we calls our function to assign values //we calls our function to assign values
let person3 = add_person(113, 114, String::from("Duck"), true); let person3 = add_person(113, 114, String::from("Duck"), true);
println!("{}\n{}\n{}\n{}", person3.id, person3.tel, person3.name, person3.alive); println!(
"{}\n{}\n{}\n{}",
person3.id, person3.tel, person3.name, person3.alive
);
let color1 = RGB(1,2,3); let colour1 = RGB(1, 2, 3);
let location1 = Coordinates(4,5,6); let location1 = Coordinates(4, 5, 6);
println!("{}{}{}", color1.0, color1.1, color1.2); println!("{}{}{}", colour1.0, colour1.1, colour1.2);
println!("{}{}{}", location1.0, location1.1, location1.2); println!("{}{}{}", location1.0, location1.1, location1.2);
//I don't know how to use //I don't know how to use
//that's why i used underscore to ignore compiler complaints //that's why i used underscore to ignore compiler complaints
let _new_unit = UnitLike; let _new_unit = UnitLike;
}
}

View file

@ -1,62 +1,58 @@
const PI:f64 = 3.14; const PI: f64 = 3.14;
// we added derivation for debugging. // we added derivation for debugging.
// this trait's going to help us for printing in this code // this trait's going to help us for printing in this code
#[derive(Debug)] #[derive(Debug)]
struct Ellipse struct Ellipse {
{
x_radius: f64, x_radius: f64,
y_radius: f64, y_radius: f64,
} }
// this implementation helps us to collect related things together // this implementation helps us to collect related things together
// in this example all things under this will be related to Ellipse struct // in this example all things under this will be related to Ellipse struct
// methods gets "self" as a first paramether, this is different from functions // methods gets "self" as a first parameter, this is different from functions
// functions like "circle" no need to get self as a parameter // functions like "circle" no need to get self as a parameter
// we call them related function, they can be used as a constructor // we call them related function, they can be used as a constructor
impl Ellipse impl Ellipse {
{ fn area(&self) -> f64 {
fn area(&self) -> f64 self.x_radius * self.y_radius * PI
{
self.x_radius*self.y_radius*PI
} }
fn x_radius(&self) -> f64 fn x_radius(&self) -> f64 {
{
self.x_radius self.x_radius
} }
fn y_radius(&self) -> f64 fn y_radius(&self) -> f64 {
{
self.y_radius self.y_radius
} }
fn can_fit(&self, second:&Ellipse) -> bool fn can_fit(&self, second: &Ellipse) -> bool {
{
self.x_radius >= second.x_radius && self.y_radius >= second.y_radius self.x_radius >= second.x_radius && self.y_radius >= second.y_radius
} }
fn circle(size:f64) -> Self fn circle(size: f64) -> Self {
{ Self {
Self { x_radius: (size), y_radius: (size) } x_radius: (size),
y_radius: (size),
} }
} }
}
fn main() fn main() {
{
println!("Hello, world!"); println!("Hello, world!");
let ellipse1 = Ellipse let ellipse1 = Ellipse {
{ x_radius: 2.0,
x_radius : 2.0, y_radius: 3.0,
y_radius : 3.0,
}; };
let ellipse2 = Ellipse let ellipse2 = Ellipse {
{ x_radius: 1.0,
x_radius : 1.0, y_radius: 2.0,
y_radius : 2.0,
}; };
let circle = Ellipse::circle(5.0); let circle = Ellipse::circle(5.0);
println!("Ellipse is {:#?}", ellipse1); println!("Ellipse is {:#?}", ellipse1);
println!("Area of the ellipse is {}", ellipse1.area()); println!("Area of the ellipse is {}", ellipse1.area());
println!("X = {}", ellipse1.x_radius()); println!("X = {}", ellipse1.x_radius());
println!("Y = {}", ellipse1.y_radius()); println!("Y = {}", ellipse1.y_radius());
println!("Is first be able to hug second: {}", ellipse1.can_fit(&ellipse2)); println!(
"Is first be able to hug second: {}",
ellipse1.can_fit(&ellipse2)
);
println!("Are of new circle = {}", circle.area()); println!("Are of new circle = {}", circle.area());
} }

View file

@ -1,47 +1,55 @@
// this is kind of null implemetation // this is kind of null implementation
// but better // but better
// because we have to specify type // because we have to specify type
// and compiler will make sure we can not be able to treat as a non null // and compiler will make sure we can not be able to treat as a non null
// <T> is generic type parameter we will learn later // <T> is generic type parameter we will learn later
// for now it can accept any type of data // for now it can accept any type of data
// "T" can be everyting // "T" can be everything
#[derive(Debug)] #[derive(Debug)]
enum Option <T> enum Option<T> {
{
None, None,
Some(T), Some(T),
} }
// this feels like event-driven programming // this feels like event-driven programming
// in this code, we basically have led states // in this code, we basically have led states
// that they have different type of associations // that they have different type of associations
// On state just keeps rgb color // On state just keeps rgb colour
// Blink and Breath keeps rgb and time value // Blink and Breath keeps rgb and time value
// Off keeps nothing // Off keeps nothing
#[derive(Debug)] #[derive(Debug)]
enum LedState enum LedState {
{ On(u8, u8, u8),
On(u8,u8,u8), Blink(u8, u8, u8, u16),
Blink(u8,u8,u8,u16), Breath(u8, u8, u8, u16),
Breath(u8,u8,u8,u16),
Off, Off,
} }
impl LedState impl LedState {
{
// this is also method, like we did in structs // this is also method, like we did in structs
fn getter(&self) -> &Self fn getter(&self) -> &Self {
{
self self
} }
}
fn main() fn export_values(&self) -> Vec<u16> {
{ match self {
LedState::On(r, g, b) => vec![*r as u16, *g as u16, *b as u16],
LedState::Blink(r, g, b, effect_time) => {
vec![*r as u16, *g as u16, *b as u16, *effect_time]
}
LedState::Breath(r, g, b, effect_time) => {
vec![*r as u16, *g as u16, *b as u16, *effect_time]
}
LedState::Off => vec![],
}
}
}
fn main() {
println!("Hello, world!"); println!("Hello, world!");
let green_light = LedState::On(0,255,0); let green_light = LedState::On(0, 255, 0);
let red_breathing = LedState::Breath(255,0,0, 10); let red_breathing = LedState::Breath(255, 0, 0, 10);
let blue_blinking = LedState::Blink(0,0,255, 5); let blue_blinking = LedState::Blink(0, 0, 255, 5);
let black = LedState::Off; let black = LedState::Off;
println!("State is = {:#?}", LedState::getter(&green_light)); println!("State is = {:#?}", LedState::getter(&green_light));
@ -49,7 +57,12 @@ fn main()
println!("State is = {:#?}", LedState::getter(&blue_blinking)); println!("State is = {:#?}", LedState::getter(&blue_blinking));
println!("State is = {:#?}", LedState::getter(&black)); println!("State is = {:#?}", LedState::getter(&black));
let null:Option<u8> = Option::None; println!("Values Are = {:#?}", green_light.export_values());
println!("Values Are = {:#?}", red_breathing.export_values());
println!("Values Are = {:#?}", blue_blinking.export_values());
println!("Values Are = {:#?}", black.export_values());
let null: Option<u8> = Option::None;
let two = Option::Some(2); let two = Option::Some(2);
println!("Value is = {:#?}", null); println!("Value is = {:#?}", null);
@ -57,7 +70,5 @@ fn main()
// this is not going to work // this is not going to work
// until we convert it // until we convert it
//println!("Total is = {}", 2+two); // println!("Total is = {}", 2+two);
}
}

View file

@ -1,21 +1,18 @@
#[derive(Debug)] #[derive(Debug)]
enum Fruits enum Fruits {
{
Apple, Apple,
Banana, Banana,
Strawberry Strawberry,
} }
enum Cake enum Cake {
{
Chocolate, Chocolate,
Caramel, Caramel,
Fruit(Fruits), Fruit(Fruits),
Tahini, Tahini,
Butter, Butter,
Vanilin, Vanillin,
} }
fn main() fn main() {
{
println!("Hello, world!"); println!("Hello, world!");
let cake1 = Cake::Chocolate; let cake1 = Cake::Chocolate;
let cake2 = Cake::Caramel; let cake2 = Cake::Caramel;
@ -24,26 +21,23 @@ fn main()
let cake5 = Cake::Fruit(Fruits::Strawberry); let cake5 = Cake::Fruit(Fruits::Strawberry);
let cake6 = Cake::Tahini; let cake6 = Cake::Tahini;
let cake7 = Cake::Butter; let cake7 = Cake::Butter;
let cake8 = Cake::Vanilin; let cake8 = Cake::Vanillin;
let cakes = [cake1,cake2,cake3,cake4,cake5,cake6,cake7,cake8]; let cakes = [cake1, cake2, cake3, cake4, cake5, cake6, cake7, cake8];
for i in cakes for i in cakes {
{ // our dear match always warn us to cover all possibilities
// our dear match always warn us to cover all posibilities
// they are like switch case but better I think // they are like switch case but better I think
// they can be useful with enums // they can be useful with enums
match i match i {
{
Cake::Chocolate => println!("Chocolate"), Cake::Chocolate => println!("Chocolate"),
Cake::Caramel => println!("Caramel"), Cake::Caramel => println!("Caramel"),
Cake::Fruit(name) => println!("Fruit {:#?}", name), Cake::Fruit(name) => println!("Fruit {:#?}", name),
Cake::Tahini => println!("Tahini"), Cake::Tahini => println!("Tahini"),
// this one is wildcard // this one is wildcard
// but when we don't want to use variable // but when we don't want to use variable
// we can use it to cover all posibilities // we can use it to cover all possibilities
// that's why it's the last one // that's why it's the last one
_ => println!("Others!"), _ => println!("Others!"),
} }
} }
}
}

View file

@ -1,14 +1,12 @@
#[derive(Debug)] #[derive(Debug)]
enum Vehicle enum Vehicle {
{
Car, Car,
Bus, Bus,
Truck, Truck,
Bicycle, Bicycle,
Scooter, Scooter,
} }
fn main() fn main() {
{
println!("Hello, world!"); println!("Hello, world!");
let vehicle1 = Vehicle::Car; let vehicle1 = Vehicle::Car;
@ -17,21 +15,17 @@ fn main()
let vehicle4 = Vehicle::Bicycle; let vehicle4 = Vehicle::Bicycle;
let vehicle5 = Vehicle::Scooter; let vehicle5 = Vehicle::Scooter;
let vehicles = [vehicle1,vehicle2,vehicle3,vehicle4,vehicle5]; let vehicles = [vehicle1, vehicle2, vehicle3, vehicle4, vehicle5];
for i in vehicles for i in vehicles {
{
// it's like match actually // it's like match actually
// but less boilerplate // but less boilerplate
// this does not force us to cover all posibilities // this does not force us to cover all possibilities
// but it can, if you want // but it can, if you want
if let Vehicle::Car = i if let Vehicle::Car = i {
{
println!("{:#?} is Car", i); println!("{:#?} is Car", i);
} } else {
else
{
println!("{:#?} is Another Thing", i); println!("{:#?} is Another Thing", i);
} }
} }
} }

View file

@ -1,6 +1,6 @@
//We can call modules with use to bring them into scope //We can call modules with use to bring them into scope
//Call them seperately //Call them separately
//use organizing_files::gift_first; //use organizing_files::gift_first;
//use organizing_files::gift_second; //use organizing_files::gift_second;