Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rust - Ownership & Borrowing

Arnaud
November 21, 2018

Rust - Ownership & Borrowing

Introduction to Rust ownership and borrowing concepts.

Arnaud

November 21, 2018
Tweet

More Decks by Arnaud

Other Decks in Programming

Transcript

  1. Stack vs Heap Stack vs Heap Stack Stack fast automatically

    desaclocated at scope end limited size pointers and primitives storage
  2. Control vs Security Control vs Security Control : optimisation Security

    : avoid memory allocation problems / memory leaks
  3. Examples Examples allocating memory and never free it dangling pointers

    keep a reference to freed memory have a reference to a moved variable (realloc) other problems...
  4. What happens when What happens when variable is copied variable

    is copied primitives : stack copy others : "move" String example copy stack representation : pointer, length, capacity disable rst variable -> 'value used here after move'
  5. Take Ownership Take Ownership copy variable into another variable pass

    variable to function return variable from function
  6. Clone Clone deep copy : stack + heap never done

    automaticaly by rust done automaticaly by rust for Stack only data (@see Copy trait) : integers, boolean, oat, character, tuple of these types
  7. Borrowing : 2 ways Borrowing : 2 ways fn(val: &String)

    no mutability any borrow as you want fn(val: &mut String) mutable other constraints
  8. String case String case String : stored in the heap

    &String : reference to a String &str : slice from a String &'static str : slice : stored in program
  9. world name value ptr len 5 index value 0 h

    1 e 2 l 3 l 4 o 5 6 w 7 o 8 r 9 l 10 d s name value ptr len 11 capacity 11
  10. String case String case as function parameter ? If we

    don't need ownership -> &str fn example(value : &str) { println!(value); }
  11. String case String case as function parameter ? If we

    need owership -> String fn example($self, value : String) { self.value = value; }
  12. String case String case &str : if the variable must

    be used outside my struct/fn &str : if the variable should be large : avoid deep copy
  13. Useful traits Useful traits Box : store data on the

    heap Deref : &String -> &str Rc : data owned by multiple variable Mutex Into Cow
  14. References References 2014 : Memory Safety in Rust : Intro

    : String vs &str : https://www.youtube.com/watch? v=WQbg6ZMQJvQ http://intorust.com/ https://hermanradtke.com/2015/05/03/string-vs- str-in-rust-functions.html