singularity

Chapter 4: Understanding Ownership

What Is Ownership?

Ownership Rules

  1. Each value in Rust has an owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped.

The String Type

Memory and Allocation

//will not work
let s1 = String::from("hello");
let s2 = s1;
println!("{s1}, world!");

//will work
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {s1}, s2 = {s2}");

let x = 5;
let y = x;
println!("x = {x}, y = {y}");

Ownership and Functions

Return Values and Scope

References and Borrowing

Mutable References

Dangling References

The Rules of References

The Slice Type

fn ch_4(){
  let mut str_lit = String::from("hello");
  str_lit.push_str(", world");

  println!("{}",str_lit);	

  let word = first_word(&str_lit);
  //str_lit.clear();

  println!("{}",word);

  fn first_word(s: &str) -> usize {
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }
    s.len()
  }  
}

String Slices

let s = String::from("hello world");

let hello = &s[0..5];
let world = &s[6..11];
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);
}

Other Slices

let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
assert_eq!(slice, &[2, 3]);