wiki/dev/lang/rust/Variable.md

44 lines
938 B
Markdown
Raw Normal View History

2023-11-18 05:44:28 +03:00
# Variables.
# Definition.
## Immutable.
Use the `let` keyword to start declaration. Types are specified after the variable name.
```rust
let x: i32 = 10;
```
Type definition is optional, so you can drop it. I suggest specifying the type for global/class/etc variables, but dropping it in local scope like functions.
```rust
let x = "This is &str"; // Type is detected automatically: &str.
```
## Mutable.
Add `mut` keyword after `let`.
```rust
let mut x: i32 = 10;
x = 12;
```
## Constants.
To declare constant, use the `const` keyword instead of `let`. Constant values always require type definition.
```rust
const NUMBER: i32 = 10;
```
# Shadowing.
You can redefine a variable with the same name but with a different type. This is useful if you cast something, but want to keep the same variable name. To do this, just declare the variable again.
```rust
let x: &str = "&str"; // &str.
let x: i32 = 10; // i32.
```