Getting Started With Rust

lil_firelord
1,604 views

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 :

divisible_by_three_between(1,101);

Playground

Functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fn main(){
divisible_by_three_between(1,31);
println!("The square of 12 is {}", square_num(12));
}
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);
}
}
}
fn square_num(n: i32) -> i32 {
n * n
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

On To Datatypes

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