Title here
Summary here
Functions are central in Rust. We’ll learn about functions with a few different examples.
fn main() {
// Call a function just as you'd expect, with
// name(args).
let res = plus(1, 2);
println!("1+2 = {}", res);
let res = plus_plus(1, 2, 3);
println!("1+2+3 = {}", res);
}
// Here's a function that takes two i32s and returns
// their sum as an i32.
fn plus(a: i32, b: i32) -> i32 {
// Rust allows implicit returns for the last expression
// in a function if you omit the semicolon.
a + b
}
// In Rust, you need to specify the type for each parameter.
// There's no shorthand for multiple parameters of the same type.
fn plus_plus(a: i32, b: i32, c: i32) -> i32 {
a + b + c
}
To run the program:
$ rustc functions.rs
$ ./functions
1+2 = 3
1+2+3 = 6
There are several other features to Rust functions. One is multiple return values, which we’ll look at next.
Key differences from the original:
main
function is defined without parameters.println!
macro instead of fmt.Println
.fn
instead of func
.->
to specify the return type, placed after the parameter list.i32
as the default integer type, similar to int
in the original.let
keyword.The structure and explanation have been maintained, but adapted to Rust’s syntax and conventions.