Rust slices in memory

In python, when i'm making a slice of array/string/etc, python create a new object in memory, so what exactly happens when I'm making the same in Rust?

let s = String::from("hello");
let slice = &s[..];

here, slice is just reference to whole object in memory(like &s), or rust create a new string object in memory?

It's a wide reference (pointer and length).

It doesn't duplicate the data.

1 Like

The signature of the Index::index trait method (that implements the bracket indexing syntax) is

fn index(&self, index: I) -> &Self::Output;

which implies that indexing can't (sensibly) be implemented by creating a new object.

(You could heap-allocate and leak it or borrow a static, but you can't return a reference to a properly memory-managed local. Thus, the returned reference can only come from within self.)