Functions
Functions in TypeScript vs Rust
Section titled “Functions in TypeScript vs Rust”TypeScript functions are defined with function or arrow syntax, with optional type annotations. In Rust, all functions are defined with fn, and all parameter and return types are required — the compiler never infers them across function boundaries. This keeps function signatures as explicit, readable contracts.
Syntax comparison
Section titled “Syntax comparison”TypeScript uses : Type for parameters and : ReturnType after the closing paren. Rust uses the same : Type syntax for parameters and -> ReturnType after the param list.
// TypeScriptfunction add(a: number, b: number): number { return a + b;}
// Rustfn add(a: i32, b: i32) -> i32 { a + b // no semicolon — this is the return value}Notice the last line has no semicolon. In Rust, a block’s final expression (without ;) is implicitly returned. Adding a semicolon turns it into a statement that returns () (unit), which would be a type error here.
function add(a: number, b: number): number { return a + b;}
function greet(name: string): string { return `Hello, ${name}!`;}
console.log(add(3, 4)); // 7console.log(greet("Alice")); // Hello, Alice!fn add(a: i32, b: i32) -> i32 { a + b // last expression, no semicolon = return value}
fn greet(name: &str) -> String { format!("Hello, {}!", name)}
fn main() { println!("{}", add(3, 4)); // 7 println!("{}", greet("Alice")); // Hello, Alice!}Try it
Section titled “Try it”fn add(a: i32, b: i32) -> i32 { a + b}
fn greet(name: &str) -> String { format!("Hello, {}!", name)}
fn main() { let sum = add(3, 4); println!("3 + 4 = {sum}"); let msg = greet("Rustacean"); println!("{msg}");}Compiling…