Rust

Rust Owned And Borrowed Types

What are Owned and Borrowed types in Rust? To know these concepts, we need to understand first what Rust Ownership and Rust References.

Get Your Head Around Rust Ownership

When we talk about ownership in Rust, we generally mean – a variable owns a value. As we assign the same value between variables, we move the value, changing the owner. While this is true for Rust Owned types, the behavior is different for Rust References (also known as Borrowed types). We pass around addresses of values somewhere in the memory instead of the values themselves.

Rust Borrowed Types

Rust Borrowed types are types that do not follow the rules for Ownership. Variables of this kind (any Rust data types) have an ampersand (&) symbol in front of them. Consider the following examples.

What happens when we try to move a reference type between variables? What do you think? Here are some Rust codes.

When we run these codes, we get the following results.

Did we move any values? Nope!

Rust Owned Types

Now, the Rust Owned types are different from Borrowed types. They follow the Rust Ownership rules. These variables contain the actual values they represent, unlike Borrowed types which have location addresses of the values they represent.

Let us modify the codes from the previous section as follows. Now we are using the String data type for pet_name and pet_owner_name!

When we run these codes, we will get the following compilation errors.

The error messages could confuse newbies who lack the basic understanding of Rust Owned and Borrowed types, even Rust Ownership rules. Notice the message error uses the root words “borrow” and “move.”

Okay, so what’s next? With a better understanding of Rust Owned and Borrowed types,  we could work with Rust more confidently. For example, now we know that we could return Owned values from functions and methods without resorting to global static variables. In the same token, we now know that we should not return a reference type from a function or method.

Are you having fun so far? There are really Owned and Borrowed types, and we didn’t make them up! Check the following codes.

Notice the call to the to_owned() method? There you go!

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like