Learn about Rust's scalar data types: integers, floats, booleans and characters.
Rust has 4 scalar data types:
We'll cover each of these in detail in this concept.
Rust has 4 scalar data types:
We'll cover each of these in detail in this concept.
Examples include i32
, u32
, i64
, and u64
.
The i
in i32
and i64
means they're "signed". They can be negative, zero, or positive.
The u
in u32
and u64
means they're "unsigned". They can only be zero or positive.
The number at the end (like 32
or 64
) indicates how much space the integer uses in memory.
let x: i32 = -5; // A signed 32-bit integer
let y: u64 = 5000000000; // An unsigned 64-bit integer
If a value is a number and a type annotation is not present, Rust will infer the type as i32
.
let x = 5; // Inferred type is 'i32'
However, if a value doesn't fit in i32
, a type annotation is required.
For example, 5000000000
is beyond the i32
limit:
// This results in a compile-time error!
// let y = 5000000000;
let y: u64 = 5000000000; // This works
Floating-point types are always signed, i.e. they support both positive and negative numbers.
f64
is a 64-bit number, offering a precision up to 15 decimal places. It's the default choice for most applications that prioritize accuracy.
f32
is a 32-bit number, offering a precision up to 7 decimal places. It's chosen when speed is more crucial than precision, such as graphics processing.
let current_position: f32 = 5.0; // Using f32 for faster graphics rendering
let pi: f64 = 3.141592653589793; // Using f64 for precise representation
When a value is a float but a type annotation isn't provided, Rust infers the type to be f64
.
let pi = 3.141592653589793; // Inferred type as 'f64'
In Rust, the boolean type is bool
.
let rust_is_cool: bool = false; // Explicit type annotation
If the value of a variable is either true
or false
, Rust will automatically infer the type to be bool
.
let rust_is_cool = true; // Inferred type as 'bool'
The char
type represents a single unicode character, like a
or 🦀
.
let rust_mascot: char = '🦀';
Note that characters need to be defined using single quotes ('
), not double quotes.
If the value of a variable is defined using single quotes (i.e. it is a "character literal"), Rust will automatically infer the type to be char
.
let rust_mascot = '🦀'; // Inferred type as 'char'
We covered the 4 scalar data types that Rust supports:
i8
, i16
…)i*
) and unsigned (u*
) integers with different sizes.f32
, f64
)f32
(single precision) and f64
(double precision).bool
)true
or false
.char
)You can learn more about these in the Data Types chapter of the Rust book.