Jump to content

Rust: 3 core concept

From Haidhi Wiki
Revision as of 02:18, 28 July 2025 by SanzSkuy (talk | contribs) (Created page with "90% "susahnya" Rust ada di 3 konsep ini == Ownership == *Every value is 'owned' by a single variable, struct, vector, etc at a time *Reassigning the value to another variable, passing it to a function, putting it into a vector, etc, '''MOVES''' the value. The old variable can't be used anymore == Borrowing == *You can create many read-only references to a value that exist at the same time *You can't move a value while a ref to the value exist *You can make writable (...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

90% "susahnya" Rust ada di 3 konsep ini

Ownership

  • Every value is 'owned' by a single variable, struct, vector, etc at a time
  • Reassigning the value to another variable, passing it to a function, putting it into a vector, etc, MOVES the value. The old variable can't be used anymore

Borrowing

  • You can create many read-only references to a value that exist at the same time
  • You can't move a value while a ref to the value exist
  • You can make writable (mutable) reference to a value ONLY IF there are no read-only references currently in use. One mutable ref to a value can exist at a time
  • You can't mutate a value through the owner when any ref (mutable or immutable) to the value exist
  • Some types of values are COPIED instead of move (numbers, bools, chars, arrays/tuple with copyable elements)

Lifetimes

  • When a variable goes out of scope, the value owned by it is dropped (cleaned up in memory)
  • Values can't be dropped if there are still active references to it
  • References to a value can't outlive the value the refer to