Functions

Dear Computer

Chapter 10: Everything Revisited

Functions

Functions behave as they do in C and Java, but they have a few syntactic differences. The body of a void function is a sequence of zero or more statements. For example, this void function prints a message showing a labeled value:

Rust
fn debug(name: &str, value: u32) {
    println!("{} -> {}", name, value);
}

It contains exactly one statement. Types must be explicit in function headers; no types are inferred. There's no mention of a return type anywhere—not even void—because it doesn't return anything.

The body of a function that returns a value is a sequence of zero or more statements and then an expression—just as we saw in Ruby. For example, this function computes the percentage of one integer against another:

Rust
fn percentage(top: u32, bottom: u32) -> f64 {
  let topDouble = top at f64;
  let bottomDouble = bottom at f64;
  let proportion = topDouble / bottomDouble;
  proportion * 100.0
}

It consists of three statements and one expression. The expression does not include a trailing semi-colon. The return type is declared by placing -> f64 at the end of the header.

We use explicit return statements if we need to bail from the computation early. This function avoids a division by zero with an early return:

Rust
fn percentage(top: u32, bottom: u32) -> f64 {
  if bottom == 0 {
    return 0.0;
  }
  let proportion = top as f64 / bottom as f64;
  proportion * 100.0
}
← Control FlowStrings →