summaryrefslogtreecommitdiff
path: root/rust/arrays.rs
diff options
context:
space:
mode:
authorCarlos Maiolino <[email protected]>2025-07-10 22:24:20 +0200
committerCarlos Maiolino <[email protected]>2025-07-10 22:24:20 +0200
commit869e68986aa8f69af6e7842260a68d1e5c6f796f (patch)
tree63b6b5ffc3d19414233d4629a533c0d9bf3cbf72 /rust/arrays.rs
parent20834dcc57537cd95260a4a22f5d91a027adfd35 (diff)
Add a bunch of code
Signed-off-by: Carlos Maiolino <[email protected]>
Diffstat (limited to 'rust/arrays.rs')
-rw-r--r--rust/arrays.rs40
1 files changed, 40 insertions, 0 deletions
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<T>, 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());
+}
+
+