3.2.0. Before the Main Text
Welcome to Chapter 3 of your Rust self-study. There are 6 sections in total:
- Variables and Mutability
- Data Types: Scalar Types (this article)
- Data Types: Compound Types
- Functions and Comments
- Control Flow:
if else - Control Flow: Loops
Through the mini-game in Chapter 2 (strongly recommended for beginners who haven't read it), you should already have learned basic Rust syntax. In Chapter 3, we will go deeper into general programming concepts in Rust.
3.2.1. Characteristics of Variables in Rust
Rust is a statically compiled language, meaning all variable types must be known at compile time.
- Based on usage, the compiler can usually infer the specific type.
- If multiple types are possible, explicit type annotation is required, otherwise compilation will fail. Example:
let guess = "6657".parse().expect("Please enter a number");
If you put this in an IDE, you will see: type error: type annotations needed. This is because 6657 can fit into multiple types such as i32, u32, etc. The compiler cannot decide which one to use. Fix:
let guess: u32 = "6657".parse().expect("Please enter a number");
3.2.2. Introduction to Scalar Types
- A scalar type represents a single value
- Rust has 4 primary scalar types:
- Integer
- Floating-point
- Boolean
- Character
3.2.3. Integer Types
- Unsigned integers (cannot represent negative values) start with
u - Signed integers (can represent negative values) start with
i - The number indicates bit size (e.g.,
u32= 32 bits)
| Length | Signed | Unsigned |
|---|---|---|
| 8-bit | i8 | u8 |
| 16-bit | i16 | u16 |
| 32-bit | i32 | u32 |
| 64-bit | i64 | u64 |
| 128-bit | i128 | u128 |
| arch | isize | usize |
isize and usize depend on architecture:
- 64-bit → equivalent to
i64/u64 - 32-bit → equivalent to
i32/u32
Commonly used for indexing collections.
3.2.4. Integer Literals
| Number literals | Example |
|---|---|
| Decimal | 98_222 |
| Hex | 0xff |
| Octal | 0o77 |
| Binary | 0b1111_0000 |
| Byte (u8 only) | b'A' |
-
_improves readability -
0x,0o,0bfor bases -
b'X'represents ASCII byte (0–255) - Default integer type:
i32
3.2.5. Integer Overflow
Example: u8 range is 0–255
- Debug mode: overflow → panic
- Release mode: wraps around (256 → 0)
3.2.6. Floating-Point Types
-
f32: single precision -
f64: double precision (default, better accuracy)
fn main(){
let machine: f32 = 6657.0721;
}
3.2.7. Numeric Operations
- Addition
+ - Subtraction
- - Multiplication
* - Division
/ - Remainder
%
3.2.8. Boolean Type
Two values: true and false, type bool
fn main(){
let machine: bool = true;
}
3.2.9. Character Type
- Represented by
char - Uses single quotes
- 4 bytes
- Unicode scalar values (supports emoji, CJK, etc.)
rust
fn main(){
let x: char = '🥵';
}
Top comments (0)