Back to course

Functions & Control Flow

Rust for Systems & Web3 Security

Logic in Rust

Functions

Declared with fn. Return values are specified with ->. The last expression in a function is returned implicitly if it doesn't have a semicolon.

rust fn add(x: i32, y: i32) -> i32 { x + y // No semicolon = return }

Control Flow

  1. if/else: Must result in a boolean.
  2. loop: Infinite loop (exit with break).
  3. while: Loop while a condition is true.
  4. for: Iterate over a collection (safest and most common).

rust for element in [10, 20, 30].iter() { println!("{element}"); }