Lesson 3 of 20

Data Types

Scalar Types

Rust has four primary scalar types:

Integers

SignedUnsignedSize
i8u88-bit
i32u3232-bit (default)
i64u6464-bit
isizeusizepointer-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:

  1. is_even(n: i32) -> bool — returns true if n is even.
  2. absolute_value(x: i32) -> i32 — returns the absolute value without using abs().
  3. hypotenuse(a: f64, b: f64) -> f64 — returns the hypotenuse of a right triangle.
  4. 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.