Rustlers Atom 1.2 - Scalar Types: Integers, bool, char, Floats

Scalar types represent a single value. Rust has four primary scalar types, and they all have a fixed, known size at compile time, which makes them very efficient.

Integers

Integers are numbers without a fractional component. They come in two main families:

  • Signed (i): can be positive or negative (e.g., i8, i32, i64).
  • Unsigned (u): can only be positive (e.g., u8, u32, u64).

The number after the i or u indicates how many bits of space the value takes up. There are also isize and usize types, which depend on the computer's architecture (64 bits on modern systems) and are primarily used for indexing collections.

  • Default: If you don’t specify a type, Rust defaults to i32.
  • Overflow: Unlike other languages, Rust handles integer overflow safely. In debug mode, the program will panic and stop. In release (optimized) mode, the value performs "two's complement wrapping" (e.g., for a u8, 255 + 1 becomes 0).
let a: i32 = -10;
let b: u64 = 98_222; // The `_` is a visual separator for readability

Floating-Point Numbers

Floating-point numbers have a decimal point. Rust has two types:

  • f32: single-precision.
  • f64: double-precision.

The default type is f64 because on modern CPUs, it’s roughly the same speed as f32 but is capable of more precision.

let x = 2.0;      // f64 (default)
let y: f32 = 3.0;  // f32

Booleans (bool)

A boolean type can only have one of two values: true or false. It takes up one byte in memory and is the engine of all conditional logic (e.g., in if expressions).

let is_rust_fun: bool = true;

Characters (char)

Rust’s char type is more powerful than in many other languages. It represents a single Unicode Scalar Value, which means it can store not only ASCII letters but also emojis, symbols, and characters from different languages.

  • char literals are specified with single quotes: 'a'.
  • To support the full Unicode spectrum, a char is always 4 bytes in size.
let c = 'z';
let z = 'ℤ';
let cat_emoji = '😻';

You'll only receive email when they publish something new.

More from GSLF
All posts