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

Rust Ownership

Rust Ownership

Computer programs must manage the memory resources they use at runtime.

Most programming languages have memory management features:

Languages like C/C++ mainly manage memory manually; developers need to manually allocate and free memory resources. But to improve development efficiency, as long as it doesn't affect program functionality, many developers don't have the habit of freeing memory in a timely manner. So manual memory management often causes resource waste.

Programs written in Java run in a virtual machine (JVM), which has the ability to automatically reclaim memory resources. But this often reduces runtime efficiency, so the JVM reclaims resources as infrequently as possible, which also causes the program to occupy larger memory resources.

Ownership is a novel concept for most developers; it is a syntactic mechanism designed by the Rust language for efficient memory use. The concept of ownership was born to let Rust more effectively analyze the usefulness of memory resources at compile time to achieve memory management.

Ownership rules

Ownership has the following three rules:

These three rules are the foundation of the ownership concept.

Next, we'll introduce concepts related to ownership.

Variable scope

We use the following program to describe the concept of variable scope:



{

    // variable s is invalid before declaration

    let s = "runoob";

    // This is the scope of variable s

}

// variable scope has ended, variable s is invalid

Variable scope is a property of a variable representing its valid domain; by default it is valid from the declaration of the variable until the end of the scope in which it resides.


Memory and allocation

If we define a variable and assign it a value, that value exists in memory. This is common. But if the data we need to store has an uncertain length (such as a string entered by a user), we cannot know the length at definition time, and thus cannot have the program allocate a fixed-length memory space at compile time. (Some say allocating as much space as possible solves the problem, but that approach is very uncivilized.) This requires a mechanism by which the program requests memory at runtime—the heap. All "memory resources" discussed in this chapter refer to the memory space occupied by the heap.

Where there is allocation there is release; a program cannot occupy a memory resource forever. Therefore, the key factor determining whether a resource is wasted is whether it is released in a timely manner.

Let's write the string sample program equivalently in C:

{

   

char

s

=

strdup

(

"runoob"

)

;

   

free

(

s

)

;

// Free the s resource

}

Obviously, Rust does not call the free function to release the resource of string s (I know this is incorrect in C, because "runoob" is not on the heap, but here we assume it is). The reason Rust doesn't explicitly show the release step is that when the variable's scope ends, the Rust compiler automatically adds a step that calls the resource-release function.

This mechanism seems simple: it merely helps the programmer add a resource-release function call in the appropriate place. But this simple mechanism can effectively solve one of the most headache-inducing programming problems in history.


Ways variables interact with data

Variables interact with data mainly in two ways: move (Move) and clone (Clone):

Mobile

Multiple variables can interact with the same data in different ways in Rust:



let x = 5;

let y = x;

This program binds the value 5 to variable x, then copies x's value and assigns it to variable y. Now there will be two values of 5 on the stack. The data in this case is of a "primitive data" type, which doesn't need to be stored on the heap; the "move" of data that is only on the stack is a direct copy, which doesn't take more time or storage space. "Primitive data" types include these:

But if the data being interacted with is on the heap, it's a different situation:



let s1 = String::from("hello");

let s2 = s1;

The first step creates a String object with value "hello". Here "hello" can be considered data of uncertain length, needing to be stored on the heap.

The second step is slightly different (this is not entirely true, only for comparison and reference):

As shown in the figure: two String objects are on the stack, each with a pointer to the "hello" string on the heap. When assigning to s2, only the data on the stack is copied; the string on the heap remains the original string.

Earlier we said that when a variable goes out of scope, Rust automatically calls the resource-release function and cleans up that variable's heap memory. But if both s1 and s2 were released, the "hello" on the heap would be freed twice, which is not allowed by the system. To ensure safety, s1 becomes invalid when assigning to s2. That's right—after assigning s1's value to s2, s1 can no longer be used. The following program is wrong:

let s1 = String::from("hello");

let s2 = s1; 

println!("{}, world!", s1); // 错误!s1 已经失效

So the actual situation is:

s1 exists in name only.


Clone

Rust tries to minimize the program's runtime cost as much as possible, so by default, large data is stored on the heap and data interaction uses the move approach. But if you need to simply copy the data for another use, you can use the second interaction method—clone.

Example

fn

main

(

)

{

   

let

s1

=

String

::

from

(

"hello"

)

;

   

let

s2

=

s1.clone

(

)

;

    println

!

(

"s1 = {}, s2 = {}"

,

s1

,

s2

)

;

}

Running result:



s1 = hello, s2 = hello

Here the "hello" on the heap is truly copied, so s1 and s2 each bind a value, and when released they are treated as two resources.

Of course, clone is only used when copying is needed, after all, copying data takes more time.


Ownership mechanics involving functions

This is the most complex case for variables.

If you pass a variable as an argument to another function, how do you handle ownership safely?

The following program describes how ownership works in this case:

Example

fn

main

(

)

{

   

let

s

=

String

::

from

(

"hello"

)

;

   

// s is declared valid

    takes_ownership

(

s

)

;

   

// s's value is passed into the function as an argument

   

// So s can be considered moved, and is invalid from here on

   

let

x

=

5

;

   

// x is declared valid

    makes_copy

(

x

)

;

   

// x's value is passed into the function as an argument

   

// But x is a primitive type and remains valid

   

// Here you can still use x but not s

}

// Function ends, x becomes invalid, then s. But s has been moved, so it doesn't need to be dropped

fn

takes_ownership

(

some_string

:

String

)

{

   

// A String parameter some_string is passed in, valid

    println

!

(

"{}"

,

some_string

)

;

}

// Function ends, parameter some_string is dropped here

fn

makes_copy

(

some_integer

:

i32

)

{

   

// An i32 parameter some_integer is passed in, valid

    println

!

(

"{}"

,

some_integer

)

;

}

// Function ends, parameter some_integer is a primitive type, no need to drop

If a variable is passed into a function as an argument, the effect is the same as a move.

Ownership mechanics of function return values

Example

fn

 main

(

)

 

{

    

let

 s1 

=

 gives_ownership

(

)

;

    

// gives_ownership moves its return value into s1

    

let

 s2 

=

 String

::

from

(

"hello"

)

;

    

// s2 is declared valid

    

let

 s3 

=

 takes_and_gives_back

(

s2

)

;

    

// s2 is moved as an argument, s3 takes ownership of the return value

}

 

// s3 becomes invalid and dropped, s2 was moved, s1 becomes invalid and dropped.

fn

 gives_ownership

(

)

 

->

 String 

{

    

let

 some_string 

=

 String

::

from

(

"hello"

)

;

    

// some_string is declared valid

    

return

 some_string

;

    

// some_string is moved out of the function as a return value

}

fn

 takes_and_gives_back

(

a_string

:

 String

)

 

->

 String 

{

 

    

// a_string is declared valid

    a_string  

// a_string is moved out of the function as a return value

}

A variable used as a function return value has its ownership moved out of the function and back to the calling site, rather than being directly dropped as invalid.


References and borrowing

References (Reference) are a concept familiar to C++ developers.

If you're familiar with pointers, you can think of it as a kind of pointer.

In essence, a "reference" is an indirect way of accessing a variable.

Example

fn

main

(

)

{

   

let

s1

=

String

::

from

(

"hello"

)

;

   

let

s2

=

&

s1

;

    println

!

(

"s1 is {}, s2 is {}"

,

s1

,

s2

)

;

}

Running result:



s1 is hello, s2 is hello

The & operator can take a variable's "reference".

When a variable's value is referenced, the variable itself is not considered invalid, because a "reference" does not copy the variable's value on the stack:

The same applies to function argument passing:

Example

fn

main

(

)

{

   

let

s1

=

String

::

from

(

"hello"

)

;

   

let

len

=

calculate_length

(

&

s1

)

;

    println

!

(

"The length of '{}' is {}."

,

s1

,

len

)

;

}

fn

calculate_length

(

s

:

&

String

)

->

usize

{

    s.len

(

)

}

Running result:



The length of 'hello' is 5.

A reference does not take ownership of the value.

A reference can only borrow (Borrow) the ownership of the value.

A reference is itself a type and has a value that records the location of another value, but the reference does not own the value it points to:

Example

fn

 main

(

)

 

{

    

let

 s1 

=

 String

::

from

(

"hello"

)

;

    

let

 s2 

=

 

&

s1

;

    

let

 s3 

=

 s1

;

    println

!

(

"{}"

,

 s2

)

;

}

This program is incorrect: because the s1 that s2 borrowed has moved its ownership to s3, s2 can no longer continue to borrow s1's ownership. If you need to use the value via s2, you must borrow again:

Example

fn

main

(

)

{

   

let

s1

=

String

::

from

(

"hello"

)

;

   

let

mut

s2

=

&

s1

;

   

let

s3

=

s1

;

    s2

=

&

s3

;

// Borrow ownership from s3 again

    println

!

(

"{}"

,

s2

)

;

}

This program is correct.

Since a reference doesn't have ownership, even if it has borrowed ownership, it only enjoys usage rights (the same as renting a house).

If you try to use borrowed rights to modify data, it will be blocked:

Example

fn

 main

(

)

 

{

    

let

 s1 

=

 String

::

from

(

"run"

)

;

    

let

 s2 

=

 

&

s1

;

    println

!

(

"{}"

,

 s2

)

;

    s2.push_str

(

"oob"

)

;

// Error, modifying a borrowed value is forbidden

    println

!

(

"{}"

,

 s2

)

;

}

In this program, s2's attempt to modify s1's value is blocked; borrowed ownership cannot modify the owner's value.

Of course, there is also a mutable way of borrowing, just like when you rent a house—if the property rules allow the owner to modify the structure and the owner states in the contract that this right is granted to you during the lease, you can renovate the house:

Example

fn

 main

(

)

 

{

    

let

 

mut

 s1 

=

 String

::

from

(

"run"

)

;

    

// s1 is mutable

    

let

 s2 

=

 

&

mut

 s1

;

    

// s2 is a mutable reference

    s2.push_str

(

"oob"

)

;

    println

!

(

"{}"

,

 s2

)

;

}

This program has no problem. We use &mut to decorate a mutable reference type.

Compared with immutable references, mutable references differ not only in permissions but also in that mutable references do not allow multiple references, while immutable references do:

Example

let

mut

s

=

String

::

from

(

"hello"

)

;

let

r1

=

&

mut

s

;

let

r2

=

&

mut

s

;

println

!

(

"{}, {}"

,

r1

,

r2

)

;

This program is incorrect because s is mutably referenced multiple times.

Rust's design of mutable references is mainly motivated by consideration of data access collisions in concurrent situations, avoiding such things at compile time.

Since one of the necessary conditions for a data access collision is that data is written by at least one user while simultaneously read or written by at least one other user, a value cannot be referenced again while it is mutably referenced.

Dangling References

This is a concept with a different name; in a programming language with pointers, it refers to a pointer that doesn't actually point to data that can really be accessed (note, not necessarily a null pointer, it could also be a freed resource). They are like ropes that have lost their hanging object, hence "dangling reference".

"Dangling references" are not allowed in the Rust language; if there are any, the compiler will catch them.

Below is a typical case of dangling:

Example

fn

main

(

)

{

   

let

reference_to_nothing

=

dangle

(

)

;

}

fn

dangle

(

)

->

&

String

{

   

let

s

=

String

::

from

(

"hello"

)

;

   

&

s

}

Obviously, as the dangle function ends, its local variable's value itself is not used as a return value and is freed. But its reference is returned, and the value that reference points to can no longer be guaranteed to exist, so it is not allowed.