From deda0d853203ed0c3b8dec1c40093b645c2faea1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=9CM=C3=9C=C5=9E?= <96421894+Tahinli@users.noreply.github.com> Date: Fri, 19 Jul 2024 22:51:20 +0300 Subject: [PATCH] feat: :sparkles: vectors --- 21-vectors/Cargo.toml | 6 +++++ 21-vectors/src/main.rs | 54 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 21-vectors/Cargo.toml create mode 100644 21-vectors/src/main.rs diff --git a/21-vectors/Cargo.toml b/21-vectors/Cargo.toml new file mode 100644 index 0000000..46314ed --- /dev/null +++ b/21-vectors/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "vectors" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/21-vectors/src/main.rs b/21-vectors/src/main.rs new file mode 100644 index 0000000..1a0ddaa --- /dev/null +++ b/21-vectors/src/main.rs @@ -0,0 +1,54 @@ +enum Types { + Number(i32), + String(String), + Float(f32), +} +fn main() { + println!("Hello, world!"); + // Actually no need to specify type but I did + let mut numbers: Vec = Vec::new(); + + // This adds element to the end of vector + numbers.push(0); + numbers.push(1); + + for _ in 0..3 { + // This tries to remove last element from vector + match numbers.pop() { + Some(popped) => println!("{}", popped), + None => eprintln!("Error: Vector is Empty"), + } + } + + // This is macro for vector + let texts = vec!["Hello", "My", "Friend"]; + + // Iteration over vector + for text in texts { + println!("{}", text); + } + + // This won't work because of borrow checker + // it prevents us to modify vector in iteration. + + // let mut texts = vec!["Hello", "My", "Friend"]; + // for text in texts { + // texts.push("Let me try"); + // } + + // This may seem like keeping different types + // actually they are belongs to same enum + + let mut different_types = vec![]; + different_types.push(Types::String(String::from("Hi!"))); + different_types.push(Types::Number(1)); + different_types.push(Types::Float(1.1)); + + for element in &different_types { + match element { + Types::Number(number) => println!("{}", number), + Types::String(string) => println!("{}", string), + Types::Float(float) => println!("{}", float), + } + } +}