Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Rust Smart Pointers

Rust Smart Pointers

Smart pointers are a common data structure in Rust; they provide extra functionality and safety guarantees to help manage memory and data.

In Rust, a smart pointer is a data type that encapsulates ownership and lifetime management of dynamically allocated memory.

Smart pointers usually wrap a raw pointer and provide extra functionality such as reference counting, ownership transfer, lifetime management, and so on.

In Rust, the standard library provides several common smart pointer types, such as Box, Rc, Arc, and RefCell.

Use cases of smart pointers:

Box Smart pointers

Box is one of the simplest smart pointers in Rust; it allows allocating a block of memory on the heap and storing a value in that memory.

Thanks to Rust's ownership rules, using Box you can create data with a known size on the heap.

Example

let

b

=

Box

::

new

(

5

)

;

println

!

(

"b = {}"

,

b

)

;

Rc Smart pointers

Rc(reference-counted pointer) allows multiple owners to share data; it uses reference counting to track the number of owners of the data and releases the data when the owner count reaches zero.

Rc is suitable for data sharing in a single-threaded environment.

Example

use

std

::

rc

::

Rc

;

let

data

=

Rc

::

new

(

5

)

;

let

data_clone

=

Rc

::

clone

(

&

data

)

;

Arc Smart pointers

Arc (atomic reference-counted pointer) is similar to Rc but can safely share data in a multi-threaded environment because it uses atomic operations to update the reference count.

Example

use

std

::

sync

::

Arc

;

let

data

=

Arc

::

new

(

5

)

;

let

data_clone

=

Arc

::

clone

(

&

data

)

;

RefCell Smart pointers

RefCell allows checking borrowing rules at runtime; it uses interior mutability to provide a safe interior mutability pattern, allowing data to be modified even when there is an immutable reference.

However, RefCell can only be used in a single-threaded environment.

Example

use

std

::

cell

::

RefCell

;

let

data

=

RefCell

::

new

(

5

)

;

let

mut

borrowed_data

=

data.borrow_mut

(

)

;

borrowed_data

=

10

;

Mutex Smart pointers

Mutex is a mutex, which guarantees that only one thread can access the data inside the Mutex at any time.

Example

use

std

::

sync

::

Mutex

;

let

m

=

Mutex

::

new

(

5

)

;

let

mut

data

=

m.lock

(

)

.unwrap

(

)

;

RwLock Smart pointers

RwLock is a read-write lock, allowing multiple readers to access data simultaneously, but exclusive when writing.

Example

use

std

::

sync

::

RwLock

;

let

lock

=

RwLock

::

new

(

5

)

;

let

read_guard

=

lock.read

(

)

.unwrap

(

)

;

Weak Smart pointers

Weak is Rc's non-owning smart pointer; it does not increase the reference count and is used to solve circular reference problems.

Example

use

std

::

rc

::

{

Rc

,

Weak

}

;

let

five

=

Rc

::

new

(

5

)

;

let

weak_five

=

Rc

::

downgrade

(

&

five

)

;

Lifetime Management of Smart Pointers

Smart pointers can help manage the lifetime of data; when a smart pointer is destroyed, it automatically frees the memory, thus avoiding problems such as memory leaks and wild pointers.

In addition, smart pointers allow specifying a particular destructor at creation time to implement custom resource management.

Example

Below is a complete simple Rust smart pointer example that uses Rc smart pointer to implement a simple reference counting feature and demonstrate multiple owners sharing data.

Example

// Import the required dependency libraries

use

std

::

rc

::

Rc

;

// Define a struct for storing data

[

derive

(

Debug

)

]

struct

Data

{

    value

:

i32

,

}

// Main function

fn

main

(

)

{

   

// Create an Rc smart pointer to share data

   

let

data

=

Rc

::

new

(

Data

{

value

:

5

}

)

;

   

// Clone the Rc smart pointer to increase the data's reference count

   

let

data_clone1

=

Rc

::

clone

(

&

data

)

;

   

let

data_clone2

=

Rc

::

clone

(

&

data

)

;

   

// Output the data's value and reference count

    println

!

(

"Data value: {}"

,

data.value

)

;

    println

!

(

"Reference count: {}"

,

Rc

::

strong_count

(

&

data

)

)

;

   

// Print the cloned Rc smart pointer

    println

!

(

"Data clone 1: {:?}"

,

data_clone1

)

;

    println

!

(

"Data clone 2: {:?}"

,

data_clone2

)

;

}

In the code above, we first defined a Data struct for storing an integer value. Then in the main function we created a Rc smart pointer to share data. Then through the Rc::clone method we cloned two smart pointers, increasing the data's reference count. Finally we printed the data's value, the reference count, and the cloned smart pointers.

Running this program, you can see the output of the data's value and reference count, as well as the cloned smart pointers. Since the Rc smart pointer uses reference counting to track the number of owners of the data, the data's reference count increases with each clone, and when the owner count reaches zero, the data is automatically released.

The output is as follows:

Data value: 5

Reference count: 3

Data clone 1: Data { value: 5 }

Data clone 2: Data { value: 5 }

Summary

Rust's smart pointers provide a safe and automated way to manage memory and shared ownership.

Smart pointers are a very important data structure in Rust; they provide a safe, flexible, and convenient way of memory management, helping programmers avoid common memory safety issues and improving code reliability and maintainability.

Smart pointers are an important part of Rust's safety model, allowing developers to write low-level code without worrying about memory safety issues.

Through smart pointers, Rust retains the control of the C language while avoiding its risks.