Rust Functions

Rust program execution begins in the traditional main function, defined like so:

Apparently the default behavior for main is to accept no parameters and return no values. [I presume there is some means of accepting command-line arguments that we will learn about later.] Interesting that the Rust designers selected the term fn for functions; the Arc dialect of Lisp uses fn as well, aiming for the right balance of terseness and legibility.

Even if main does not accept any parameters or return any values, Rust functions in general certainly can. And unlike with regular variable declarations, the types of function parameters and return values must be explicitly stated:

A Rust function returns the final expression in the function. Note that in the function above, the expression x + 42 is just that: an expression. As in C, concluding an expression with a semicolon turns it into a statement, but in the context of a function return value, we just want the plain expression. We could explicitly write an actual return statement:

and while this might make us long-time C programmers feel happy, the Rust designers deem it “poor style” when a final expression return value would work instead. (Using a return statement may be appropriate in other cases, if you want to return out of a function before reaching the end of the function.)

Rust offers function pointers in a way that looks much cleaner than in C. We can declare a variable to be of a function type with a particular function signature:

This declares f to be of type, function that accepts a signed 32-bit integer and returns a 32-bit integer. This also appears to be an exception to the rule that variables must be initialized, as the above line of code works as-is. But we can initialize it with a value of a function, assuming we have defined a function that matches that type:

We could also let the Rust compiler just infer the type of the function when declaring the function pointer:

Using function pointers in C isn’t that hard once you get used to it, but Rust’s syntax is a lot easier to look at!

More: read the Functions chapter in The Rust Programming Language.

Leave a Reply

Your email address will not be published. Required fields are marked *