Lesson 3 of 20
Data Types
Scalar Types
Rust has four primary scalar types:
Integers
| Signed | Unsigned | Size |
|---|---|---|
i8 | u8 | 8-bit |
i32 | u32 | 32-bit (default) |
i64 | u64 | 64-bit |
isize | usize | pointer-sized |
Floating Point
f64 (64-bit, default) and f32 (32-bit). Rust's math methods live on the types:
let x: f64 = 2.0;
let y = x.sqrt(); // 1.4142...
let z = x.powi(3); // 8.0 (integer power)
Boolean and Char
let t: bool = true;
let c: char = 'z'; // Unicode scalar value
Type Casting
Use as to cast between numeric types:
let x: i32 = 42;
let y = x as f64; // 42.0
let z = 3.9f64 as i32; // 3 (truncates)
Compound Types
Tuples
Fixed-length heterogeneous collections. Access with .0, .1, etc.:
let t = (500, 6.4, true);
let (x, y, z) = t; // destructuring
println!("{}", t.0); // 500
Arrays
Fixed-length, same type. Stack-allocated:
let a = [1, 2, 3, 4, 5];
let b: [i32; 3] = [0; 3]; // [0, 0, 0]
println!("{}", a[0]); // 1
Your Task
Implement these functions:
is_even(n: i32) -> bool— returns true ifnis even.absolute_value(x: i32) -> i32— returns the absolute value without usingabs().hypotenuse(a: f64, b: f64) -> f64— returns the hypotenuse of a right triangle.swap<T: Copy>(t: (T, T)) -> (T, T)— swaps the two elements of a tuple.
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.