diff options
| author | Carlos Maiolino <[email protected]> | 2025-07-10 22:24:20 +0200 |
|---|---|---|
| committer | Carlos Maiolino <[email protected]> | 2025-07-10 22:24:20 +0200 |
| commit | 869e68986aa8f69af6e7842260a68d1e5c6f796f (patch) | |
| tree | 63b6b5ffc3d19414233d4629a533c0d9bf3cbf72 /rust/slices.rs | |
| parent | 20834dcc57537cd95260a4a22f5d91a027adfd35 (diff) | |
Add a bunch of code
Signed-off-by: Carlos Maiolino <[email protected]>
Diffstat (limited to 'rust/slices.rs')
| -rw-r--r-- | rust/slices.rs | 39 |
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); +} |
