RUST AND SCALA FOR BEGINNERS: 2 BOOKS IN 1 - Learn Coding Fast! RUST AND SCALA Crash Course, A QuickStart Guide, Tutorial Book by Program Examples, In Easy Steps! by TAM SEL

RUST AND SCALA FOR BEGINNERS: 2 BOOKS IN 1 - Learn Coding Fast! RUST AND SCALA Crash Course, A QuickStart Guide, Tutorial Book by Program Examples, In Easy Steps! by TAM SEL

Author:TAM SEL [SEL, TAM]
Language: eng
Format: azw3
Published: 2020-01-06T16:00:00+00:00


In the above example, we have seen that the immutable value cannot be borrowed mutably. But, RefCell is the one way to achieve the interior mutability.

Keeping Track of Borrows at Runtime with RefCell<T>

RefCell<T> consists of two methods that keep track of borrows at runtime:

borrow(): The borrow() method returns the smart pointer of type Ref<T>.

borrow_mut(): The borrow_mut() method returns the smart pointer of type RefMut<<T>.

Some Important Points:

The RefCell<T> keeps a record of how many Ref<T> and Refmut<T> smart pointers are currently active.

Whenever the borrow() method is called, then the RefCell<T> increases the count of how many immutable borrows are active. When the Rc<T> goes out of the scope, then RefCell<T> decreases the count by one.

The RefCell<T> lets us have many immutable borrows but one mutable borrow at a time, just as compile-time borrowing rules. If we violate this rule, then the RefCell<T> will panic at runtime.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.