Declaring Functions
Part of the Fundamentals section of Coddy's Rust journey. Lesson 49 of 75.
A function is a sequence of code that has a name. The purpose of a function is to reuse a piece of code multiple times.
For example, take a look at this code:
println!("Welcome to Coddy");
println!("New session...");
println!("Welcome to Coddy");
println!("Another session...");
println!("Welcome to Coddy");We use the same code println!("Welcome to Coddy") over and over again. Another issue with this code is that if we wanted to change the message: Welcome to Coddy to something different, like "Welcome aboard" it would have to change 3 different lines of code. To solve this issue, we will use functions.
To declare a function, we use the following syntax:
fn function_name(parameters) {
// code
}For our example, we will create a function named greet and it will look like this:
fn greet() {
println!("Welcome to Coddy");
}To use/call/execute the function, we write greet();:
greet();
println!("New session...");
greet();
println!("Another session...");
greet();This will result in the same output as above.
Note: In Rust, the compiler allows you to call a function before it is declared in the file. However, it is recommended convention to write the function definition before its call/execution.
Challenge
EasyWrite a program that gets one input, a number. The input number indicates how many times to execute the below function.
Create a function that calculates the sum of all of the numbers between 1 and 1000 (including) and prints it, name the function however you like.
Note! As a recommended convention, write the function before its call/execution statements in your code.
Try it yourself
use std::io;
// Function declaration
fn sum_numbers() {
// Complete Function
}
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();
for _ in 0..n {
// Call the function n times
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 311Functions
Declaring FunctionsParameters and ArgumentsReturn ValuesMultiple Return ValuesRecap - Sigma FunctionRecap - Validation Function3Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic InputPractice on your own: Online Rust compiler