rust / beginner
Snippet
Understanding Scalar Types in Rust
Rust has several scalar types representing single values. Integers come in signed (i) and unsigned (u) variants with sizes from 8 to 64 bits. Signed integers use two's complement representation. Floating-point numbers are either f32 (32-bit) or f64 (64-bit, default). Booleans are one byte and represented as `true` or `false`. Characters are Unicode scalar values four bytes in size, denoted with single quotes. Rust does not perform implicit type conversion between numeric types, so you must use the `as` keyword for explicit casting.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fn main() {let integer: i32 = -42;let unsigned: u8 = 255;let floating: f64 = 3.14159;let is_active: bool = true;let letter: char = 'R';println!("Integer (i32): {}", integer);println!("Unsigned (u8): {}", unsigned);println!("Float (f64): {:.2}", floating);println!("Boolean: {}", is_active);println!("Character: {}", letter);let sum = (floating as f64) + (integer as f64);println!("Sum of float and int: {}", sum);}
Breakdown
1
let integer: i32 = -42;
Signed 32-bit integer, can hold negative and positive values
2
let unsigned: u8 = 255;
Unsigned 8-bit integer, range 0-255
3
let floating: f64 = 3.14159;
64-bit floating point number (double precision)
4
let is_active: bool = true;
Boolean value, either true or false
5
let letter: char = 'R';
Character type, holds a single Unicode character
6
(floating as f64)
Explicit type cast using 'as' keyword