Scalar data types hold a single value at a time. They help us store simple pieces of information like numbers or characters.
0
0
Scalar data types in Rust
Introduction
When you want to store a single number like age or temperature.
When you need to keep a true or false value for a condition.
When you want to store a single letter or symbol.
When you want to represent a small piece of data like a byte or integer.
When you want to perform math or logic with simple values.
Syntax
Rust
let variable_name: data_type = value;
Use let to create a variable.
Specify the data type after a colon : (optional, Rust can infer it).
Examples
This creates a 32-bit integer variable
x with value 5.Rust
let x: i32 = 5;This creates a 64-bit floating-point number
y with value 3.14.Rust
let y: f64 = 3.14;This creates a boolean variable
is_active set to true.Rust
let is_active: bool = true;This creates a character variable
letter holding the letter 'A'.Rust
let letter: char = 'A';
Sample Program
This program creates four scalar variables: an unsigned 8-bit integer for age, a 32-bit float for temperature, a boolean for rain status, and a character for grade. It then prints each value.
Rust
fn main() {
let age: u8 = 30;
let temperature: f32 = 36.6;
let is_raining: bool = false;
let grade: char = 'B';
println!("Age: {}", age);
println!("Temperature: {}", temperature);
println!("Is it raining? {}", is_raining);
println!("Grade: {}", grade);
}OutputSuccess
Important Notes
Rust has several integer types like i8, i16, i32, i64, and unsigned versions like u8.
Floating-point types are f32 and f64, with f64 being more precise.
Boolean values can only be true or false.
Characters in Rust are 4 bytes and can hold Unicode symbols.
Summary
Scalar types store one simple value at a time.
Common scalar types are integers, floats, booleans, and characters.
Use scalar types to represent basic data like numbers, true/false, or single letters.