From 869e68986aa8f69af6e7842260a68d1e5c6f796f Mon Sep 17 00:00:00 2001 From: Carlos Maiolino Date: Thu, 10 Jul 2025 22:24:20 +0200 Subject: Add a bunch of code Signed-off-by: Carlos Maiolino --- rust/arrays.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 rust/arrays.rs (limited to 'rust/arrays.rs') diff --git a/rust/arrays.rs b/rust/arrays.rs new file mode 100644 index 0000000..2e22751 --- /dev/null +++ b/rust/arrays.rs @@ -0,0 +1,40 @@ +// ARRAYS - similar than C +// +//array size must be known at compile time +// +// signature: [T; length] +// let var: [T; length] = foo + +fn main() { + let arr: [i32; 5] = [1, 2, 3, 4, 5]; + + // Implicit declaration: + let myarr = ['a', 'b', 'c']; + println!("{}", arr.len()); + + // Initialize all elements: [value, num of elements] + let auto_arr: [i32; 100] = [1; 100]; + + for c in arr { + print!("{} ", c); + } + + for c in myarr { + print!("{} ", c); + } + println!(""); + + println!("array sizes: arr {} myarr {}", std::mem::size_of_val(&arr), + std::mem::size_of_val(&myarr)); + + // Accessing specific elements in an array can be done via indexing or .get method + // .get method returns an Option, so we also need to use unwrap: + + let many: [i32; 10] = [1, 3, 4, 6, 8, 34, 60, 44, 94, 10]; + + // great, either many[3] or &many[3] works, shrug + println!("Via index: {} - Via get method: {}", + &many[3], many.get(6).unwrap()); +} + + -- cgit v1.2.3