Rust for typescript devs Part 2: Immutabilty

This is the second post in “Rust for typescript devs series”.
Read the intro post here

Immutability is a concept that TypeScript developers encounter frequently, especially when dealing with const variables or functional programming patterns. In Rust,…


This content originally appeared on DEV Community and was authored by Rhl

This is the second post in "Rust for typescript devs series".
Read the intro post here

Immutability is a concept that TypeScript developers encounter frequently, especially when dealing with const variables or functional programming patterns. In Rust, immutability is not just a recommendation; it's the default behavior for all variables. This emphasis on immutability is a cornerstone of Rust's design, contributing to its reputation for safety and performance. In this section, we’ll explore how Rust’s approach to immutability compares to what you’re used to in TypeScript and why this concept is so integral to writing reliable Rust code.

Immutability by Default

TypeScript:

In TypeScript, you use the const keyword to declare variables that should not be reassigned. However, if you use let, the variable is mutable by default, meaning its value can be changed after it's been assigned.

typescript

const immutableValue = 10;
// immutableValue = 20; // Error: Assignment to constant variable.

let mutableValue = 10;
mutableValue = 20; // This works just fine.

Rust:

In Rust, all variables are immutable by default. If you want a variable to be mutable, you must explicitly mark it with the mut keyword.

rust


let immutable_value = 10;
// immutable_value = 20; // Error: cannot assign twice to immutable variable

let mut mutable_value = 10;
mutable_value = 20; // This works just fine.

Key Difference:
While TypeScript gives you the option to make variables immutable using const, Rust takes the opposite approach by making all variables immutable unless explicitly stated otherwise with mut. This default immutability reduces the likelihood of unintended side effects, making your code more predictable and easier to reason about.

The Benefits of Immutability

Immutability plays a crucial role in maintaining the integrity of your data and avoiding bugs caused by unintended modifications. This is particularly important in concurrent programming, where multiple threads might access and modify the same data. Rust's emphasis on immutability helps prevent such issues at compile time, ensuring that your code is safe from data races and other concurrency problems.

TypeScript:
In TypeScript, immutability is often encouraged in functional programming patterns or when working with Redux in React, but it’s not enforced by the language.

typescript

const add = (a: number, b: number): number => a + b;

const immutableObject = { name: "Alice" };
// immutableObject.name = "Bob"; // Error: Cannot assign to 'name' because it is a read-only property

Rust:
Rust enforces immutability at the language level, making it an integral part of writing safe and efficient code. When you declare a variable without mut, you’re assured that its value will not change, making your code more predictable and less prone to bugs.

rust

fn add(a: i32, b: i32) -> i32 {
    a + b
}

let immutable_object = String::from("Alice");
// immutable_object.push_str("Bob"); // Error: Cannot borrow immutable object as mutable

In Rust, immutability isn’t just a best practice; it’s a default. This default behavior ensures that your variables remain unchanged unless explicitly stated otherwise, leading to safer and more reliable code. This is especially beneficial in concurrent and multi-threaded environments, where mutable shared state can lead to complex and hard-to-debug issues.

Mutability with mut
There are times when you do need to mutate a variable, and Rust allows for this, but only when you explicitly declare your intent by using the mut keyword.

TypeScript:

typescript

let counter = 0;
counter += 1; // This is allowed because 'let' allows reassignment

Rust:

let mut counter = 0;
counter += 1; // This is allowed because 'mut' explicitly allows mutation

Key Difference:

In TypeScript, let variables are mutable by default, whereas in Rust, mutability must be explicitly declared. This explicitness in Rust helps prevent accidental mutations, making the code more transparent and easier to maintain.

Immutability in Function Parameters

Another area where Rust emphasizes immutability is in function parameters. By default, all function parameters in Rust are immutable, which aligns with the language’s general preference for immutability.

TypeScript:

In TypeScript, function parameters are mutable by default, meaning you can change their values within the function body, although it’s generally not a recommended practice.

typescript

function increment(x: number): number {
    x += 1; // This is allowed, but often not recommended
    return x;
}

Rust:

In Rust, if you want to modify a parameter within a function, you need to explicitly pass it as a mutable reference. Otherwise, it remains immutable by default.

rust

fn increment(mut x: i32) -> i32 {
    x += 1;
    x
}

Rust’s immutability by default extends to function parameters, ensuring that you can trust the values passed to functions to remain unchanged unless explicitly declared otherwise. This further reinforces the safety and predictability of your code.

Immutability is more than just a coding practice in Rust; it’s a fundamental aspect of the language’s design. By making variables immutable by default, Rust encourages you to write code that is safer, more predictable, and easier to understand. As a TypeScript developer, you’re already familiar with the concept of immutability, but Rust takes it to the next level by making it the default behavior.

That is it for this blog, in the next blog in the series we are going to look at strings in rust and how they compare with strings in typescript


This content originally appeared on DEV Community and was authored by Rhl


Print Share Comment Cite Upload Translate Updates
APA

Rhl | Sciencx (2024-08-29T06:30:11+00:00) Rust for typescript devs Part 2: Immutabilty. Retrieved from https://www.scien.cx/2024/08/29/rust-for-typescript-devs-part-2-immutabilty/

MLA
" » Rust for typescript devs Part 2: Immutabilty." Rhl | Sciencx - Thursday August 29, 2024, https://www.scien.cx/2024/08/29/rust-for-typescript-devs-part-2-immutabilty/
HARVARD
Rhl | Sciencx Thursday August 29, 2024 » Rust for typescript devs Part 2: Immutabilty., viewed ,<https://www.scien.cx/2024/08/29/rust-for-typescript-devs-part-2-immutabilty/>
VANCOUVER
Rhl | Sciencx - » Rust for typescript devs Part 2: Immutabilty. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/29/rust-for-typescript-devs-part-2-immutabilty/
CHICAGO
" » Rust for typescript devs Part 2: Immutabilty." Rhl | Sciencx - Accessed . https://www.scien.cx/2024/08/29/rust-for-typescript-devs-part-2-immutabilty/
IEEE
" » Rust for typescript devs Part 2: Immutabilty." Rhl | Sciencx [Online]. Available: https://www.scien.cx/2024/08/29/rust-for-typescript-devs-part-2-immutabilty/. [Accessed: ]
rf:citation
» Rust for typescript devs Part 2: Immutabilty | Rhl | Sciencx | https://www.scien.cx/2024/08/29/rust-for-typescript-devs-part-2-immutabilty/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.