Functions

1

Functions, Parameters, and Return Values

6 minute

For a C programmer, a Rust function first looks like the same idea with syntax moved around:

int add(int a, int b)
{
    return a + b;
}

In Rust:

fn add(a: i32, b: i32) -> i32 {
    a + b
}

They do the same work, but Rust functions introduce a few early habits:

  • parameter names come before types
  • return types come after ->
  • the final expression can be the return value
  • return is often used for early exits
  • functions without useful return values return ()
  • C out parameters and return codes often become Rust return values and Result

This is not full ownership theory, but it immediately affects how you write a first library function.

Read More