पाठ 6 / 25

Functions and Modules

Typed signatures, last expression returns.

Signatures are contracts

Functions declare parameter and return types explicitly: fn area(w: f64, h: f64) -> f64 { w * h }; the final expression without a semicolon is the return value (return exits early). Rust has no function overloading or default arguments; use different names, Option parameters or builder patterns. Functions are grouped in modules; use brings items into scope, and pub exposes them. Closures (|x| x + 1) are anonymous functions that can capture their environment.

Functions, closures and modules (sketch)

Shape of common declarations; compiles in a project with an orders module. Not run as a whole here.

mod orders {
    pub fn total(prices: &[u32]) -> u32 {
        prices.iter().sum()          // last expression is returned
    }

    fn tax(amount: u32) -> u32 {     // private to this module
        amount * 18 / 100
    }
}

use orders::total;

fn main() {
    let add_shipping = |t: u32| t + 50;   // a closure
    println!("{}", add_shipping(total(&[120, 899])));
}

Take &str and slices as parameters

Accepting &str and &[T] instead of String and Vec lets callers pass many kinds of data without copying.

त्वरित जाँच: What does a Rust function return if its body ends with an expression without a semicolon?

  • The first statement
  • Nothing
  • An error
  • The value of that expression
Answer

The value of that expression — Implicit return of the tail expression.