Mutable variable assignment and a fun return value in Rust — how to Rust

Ly Channa
2 min readApr 17, 2024

--

Understand how Rust handles assignments to mutable variables

In Rust, the ability to assign the return value of a function to a mutable variable (mut) is governed by the ownership and borrowing rules of the language. Rust is designed to provide safety guarantees about memory usage and concurrency without needing a garbage collector. Here's how it handles assignments to mutable variables

1. Ownership Transfer

When a function returns a value, the ownership of that value is transferred to the caller. This means that once the value is returned, the caller fully owns it and can decide how to use it, including making it mutable.

2. Mutable Variables (mut)

Declaring a variable as mutable in Rust is done by prefixing the variable name with mut. This tells the Rust compiler that the value bound to this variable can change.

fn create_file(name: &str) -> File {
let file = File {
name: String::from(name)
}

file
}

let mut x = create_file("dummy.txt");

In the code snippet above, some_function() returns a value, and Rust allows the caller to take ownership of this value. By declaring x as mut, you are explicitly stating that x can be modified later.

3. Immutable by Default

Rust variables are immutable by default, which means they cannot be changed once they are set. This default behavior helps in writing safer and more concurrent code. However, you can opt out of this immutability by using mut when you need to modify the value after it's been initialized.

4. Flexibility in Variable Declaration

The decision to make a variable mutable or immutable in Rust does not depend on the function or the value it returns but on how the caller intends to use the value. Even if the function returns an immutable value, the caller can decide to make the variable storing this value mutable if the situation requires it.

//my_age is an immutable.
let my_age = 36u8

// my_frend_age has the same value as my_age but mutable.
let mut my_frend_age = my_age;

Conclusion

This design encourages developers to think about where data should be mutable, thus preventing many common programming errors, such as race conditions in concurrent programming. The ability to assign a function’s return value to a mutable variable is a simple extension of Rust’s ownership system, where the caller gets full control over the returned value, including whether or not it should be mutable.

--

--

Ly Channa

Highly skilled: REST API, OAuth2, OpenIDConnect, SSO, TDD, RubyOnRails, CI/CD, Infrastruct as Code, AWS.