Rust, Software Development

How To Modify Struct Instance In A Function in Rust

This post shows how to modify a struct instance in a function. It uses the mutable shared borrowing to pass a mutable reference as an argument to a function.

Struct And Instance

Consider the following Person struct. It has two fields – name and email – of String type.

To create an instance of this struct, we use the struct expression and assign it to a mutable variable. A mutable variable uses the mut keyword between the let keyword and the variable name.

At this point, we have an instance whose content we can modify anywhere in the same code block. If we want to modify it within a function, we need to define a function accordingly.

Modify In A Function

When we want to modify a struct instance passed as an argument to a function, we need to define the function parameter prefixed with &mut  and space. Moreover, we need to prefix the argument with &mut and space when invoking the function. Consider the following function.

Notice the codes used &mut Person for the person parameter.

Pass Struct Instance To Function

Now, we invoke the function with a mutable reference to the struct instance.

Notice the codes used &mut person_1 as the argument. The codes output the following.

Complete Rust Codes

In summary, we pass a mutable reference as an argument to a function. There are three points to remember. First, create a mutable instance of a struct using the mut keyword. Second, create a function with a parameter definition of param_name &mut [struct-type] as an argument to a function. Third, pass the reference of the mutable instance prefixed with &mut  and space. The following is the complete source code file.

When we don’t want to modify a struct instance in a function, we omit all the mut keywords used. We change the update_name_and_email function and the way other codes call it, as shown below.

We run the function as follows.

We used Rust 1.42.0 for this post.

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