Functions

Rust functions are like Perl subroutines. They don't have to be pure functions (mathematical functions).

Named functions in Rust are created with the keyword fn. We've already seen one of these; the "hello world" program used a main function.

fn main() {
    println!("Hello, World!");
}

In Perl, we don't have an explicit main, though it is there implicitly (we are in package main unless we say otherwise).

In Rust, there is also a separate syntax for closures. In Perl, we use keyword sub for both named and anonymous subroutines.

RustPerl
fnsub
closuressub
traitsroles

In Rust, function signatures are the one place where there is never any type inference. We always have to say the types of our arguments and of our return value. This is kind of nice, as it serves as a form of documentation.

If you've done any Haskell, you know that it will infer types in the function definitions as well. But having that information at hand is so valuable that Haskell programmers usually include a type signature declaration even though it's optional to do so.

In Haskell, it's a best practice. In Rust, it's required.