Skip to content

Latest commit

 

History

History
34 lines (24 loc) · 1.06 KB

05.md

File metadata and controls

34 lines (24 loc) · 1.06 KB

Create and use functions

Background

Next up we want to take a look at how we create functions that can then be reused inside our program.

Generally, functions in Rust are declared using the fn keyword, followed by its name, followed by parenthesis, followed by possible parameters and its annotations, followed by the function's return type:

fn some_function(a: u32, b: u32) -> u32 {
  // ...
}

The type annotations here (u32) describe that the input parameters and the function's return type is an unsigned 32 bit integer value. There are many other data types in Rust that can be used. In fact, it's common to create custom ones.

Such a function can then be used later on, by calling it:

let result = some_function(3, 4);

Exercise

Create a new package sum inside src using the cargo new command. Then create a function sum(a: u32, b: 32) -> u32 that adds two given numbers and returns them. After that call that function inside the package's main() with parameters of your choice and output the result using the println macro.