Understanding rust Ownership
The slice type
slice type does not have ownership
let s = String::new("Hello world");
// will contain "Hello", right index 5 is exclusive
let hello = &s[0..5];
// same as above
let hello = &s[..5];
let world = &s[6..11];
// from index 6 to end of
let world = &s[6..];
let len = s.len();
// whole String
let slice = &s[0..len];
// same as above
let slice = &s[..];
String literals are slices
let s = "Hello, world";
// s is inferred to &str
// &str is an immutable reference
String slices as parameters
fn first_word(s: &String) -> &str {
// better the following as we can use the same function on both `&String` and `&str`:
fn first_word(s: &str) -> &str {
// by passing a string slice takes advantage of deref coercions
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
fn main() {
let my_string = String::from("hello world");
// `first_word` works on slices of `String`s, whether partial or whole
let word = first_word(&my_string[0..6]);
let word = first_word(&my_string[..]);
// `first_word` also works on references to `String`s, which are equivalent
// to whole slices of `String`s
let word = first_word(&my_string);
let my_string_literal = "hello world";
// `first_word` works on slices of string literals, whether partial or whole
let word = first_word(&my_string_literal[0..6]);
let word = first_word(&my_string_literal[..]);
// Because string literals *are* string slices already,
// this works too, without the slice syntax!
let word = first_word(my_string_literal);
}