Variables are used to store data in a program. Here’s an overview of variables in Rust:
- The `let` keyword is used to declare variables in Rust, followed by the variable name and type.
- The variable type must be declared at the time of declaration and cannot be changed later.
- Variables are either mutable (can be changed) or immutable (cannot be changed). Mutable variables are declared using `let` `mut`, while immutable variables are declared using just `let`.
- Rust uses static typing, meaning that the variable type must be known at compile time.
let x: i32 = 5; // Declares an immutable i32 variable with value 5
let mut y: i32 = 10; // Declares a mutable i32 variable with value 10
y = 20; // Changes the value of y to 20
In Rust, variables have a specific type, which must be declared when the variable is declared. Rust has several built-in types, including:
- Integers:
i8
,i16
,i32
,i64
,u8
,u16
,u32
,u64
,isize
,usize
- Floating-point numbers:
f32
,f64
- Boolean values:
bool
- Characters:
char
- Strings:
String
- Arrays:
[T; N]
, whereT
is the type of the elements andN
is the number of elements in the array - Tuples: A collection of values of different types
- Structs: A collection of named fields, each with a specified type
- Enums: A type with a set of named variants
- Option: An enumeration used to express the possibility of the absence of a value
Here’s an example of using several of these types in Rust:
let x: i32 = 5;
let y: f64 = 3.14;
let z: bool = true;
let a: char = 'a';
let s: String = "Hello, World!".to_string();
let arr: [i32; 5] = [1, 2, 3, 4, 5];
let tup: (i32, f64, char) = (10, 20.0, 'c');
struct Point {
x: i32,
y: i32,
}
enum Color {
Red,
Green,
Blue,
}
let p = Point { x: 10, y: 20 };
let c = Color::Red;
In Rust, the type of a variable must be declared when it is declared, and it cannot be changed later on. This ensures that the type of a variable is known at compile-time, making it easier to catch type-related errors early in the development process. Additionally, Rust’s strict typing system helps prevent type-related bugs, making it easier to write safe and efficient code.