summaryrefslogtreecommitdiff
path: root/rust/slices.rs
diff options
context:
space:
mode:
Diffstat (limited to 'rust/slices.rs')
-rw-r--r--rust/slices.rs39
1 files changed, 39 insertions, 0 deletions
diff --git a/rust/slices.rs b/rust/slices.rs
new file mode 100644
index 0000000..096fe56
--- /dev/null
+++ b/rust/slices.rs
@@ -0,0 +1,39 @@
+// SLICES
+//
+// Contiguous sequence of elements in a collection
+// enables us to borrow part of a collection without
+// taking ownership of the whole thing
+//
+// can be created from arrays, vectors, strings and
+// any other collection implementing the 'Deref' trait
+//
+// slices length are not known at compile time
+//
+// Type signature: &[T]
+
+fn main() {
+
+ let a: [i32; 5] = [36234689, 2, 3, 4, 5];
+
+ // correct way to annotate slice types
+ let slice: &[i32] = &a[..4];
+
+ println!("{:?}", slice);
+
+ // Slices are two-words object (occupies 2-words in memory).
+ // first word is the data pointer, second is the slice length:
+ let s2: &[i32] = &a[..5];
+
+ // If this is a 64-bit machine, this should return 16 bytes.
+ // as we have 64-bit words.
+ println!("Slice size: {} bytes", std::mem::size_of_val(&s2));
+
+ // Slices are byte indexed, the index '[foo]' is actually a byte
+ // number, not member number.
+ //
+ // ^ I don't think this is correct, but the course made it work
+ // with strings, perhaps it is only valid for string type, shrug.
+ let s3: &[i32] = &a[0..1];
+ let b: i32 = s3[0];
+ println!("{:?}", b);
+}