Ownership
https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
For many types in Rust, there are owned and non-owned variants. Owned means not behind a reference, can be passed to different functions without worrying about lifetimes:
- Strings: String is owned, &str is a reference
- Paths: PathBuf is owned, &Path is a reference
- Collections: Vec
is owned, &[T] is a reference
Rust has slices - they're a reference to multiple contiguous elements.
You can borrow a slice of a vector, for example:
fn main() { let v = vec![1, 2, 3, 4, 5]; let v2 = &v[2..4]; println!("v2 = {:?}", v2); } // output: // v2 = [3, 4]
Borrowing rules apply to slices.
fn tail(s: &[u8]) -> &[u8] { &s[1..] } fn main() { let x = &[1, 2, 3, 4, 5]; let y = tail(x); println!("y = {:?}", y); }
&str values are really slices.
fn file_ext(name: &str) -> Option<&str> { // this does not create a new string - it returns // a slice of the argument. name.split(".").last() } fn main() { let name = "Read me. Or don't.txt"; if let Some(ext) = file_ext(name) { println!("file extension: {}", ext); } else { println!("no file extension"); } }