乐闻世界logo
搜索文章和话题

How do you declare and initialize variables in Rust?

1个答案

1

In Rust, declaring and initializing variables is primarily done using the let keyword. Rust variables are immutable by default, meaning that once a variable is assigned a value, its value cannot be changed unless you explicitly specify it as mutable using the mut keyword.

Declaring Immutable Variables

To declare an immutable variable in Rust, use the following syntax:

rust
let variable_name = value;

For example, declaring an immutable integer variable:

rust
let x = 5;

In this example, x is an immutable integer variable initialized to 5.

Declaring Mutable Variables

If you need to modify a variable's value, declare it as mutable using the mut keyword:

rust
let mut variable_name = value;

For example, declaring a mutable integer variable:

rust
let mut y = 5; y = 10; // Correct, as y is mutable

In this example, y is initially set to 5 and then changed to 10.

Using Type Annotations

Although Rust can infer variable types automatically, you may explicitly specify them using type annotations:

rust
let variable_name: type = value;

For example, explicitly declaring an integer variable:

rust
let z: i32 = 20;

In this example, z is explicitly declared as a 32-bit integer and initialized to 20.

Summary

By using the let keyword (along with optional mut and type annotations), you can flexibly declare and initialize variables in Rust. Immutability (the default behavior) helps prevent errors and inconsistencies in the code, while mutability can be enabled through explicit declaration when needed. These features make Rust both safe and flexible.

2024年8月7日 14:53 回复

你的答案