Getting Started With Rust


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

#Functions in Rust

Functions in rust begin with the fn keyword, followed by the function name, arguments, a return type if the function has one, and then the code block.

fn functionName(argument1: i32, argument2: i32) -> bool {
	// Function code here

In the above function, the name is functionName, it has two arguments of the type i32 and returns a bool. Note that return types are signified after the -> operator.

If there is no return value, you can omit the type altogether, but if there are no arguments, you must still list parentheses:

fn functionNameTwo() {
	// Function code here

To follow in last lesson's path, let's rewrite our loop in to a function:

fn divisible_by_three_between(min: i32, max_exclusive: i32) {
	for x in min..max_exclusive {
		if x % 3 == 0 {
			println!("{} is divisible by 3", x);

In this example, we receive two 32 bit integers, i32, which are the min and max (exclusive) of the range we want to check. Then we use a for-in loop with the two inputs and check each value in the range if it is evenly divisible by three and print a statement accordingly.

Calling this function is as easy as :




On To Datatypes

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content