Menu
Coddy logo textTech

Declaring Functions

Part of the Fundamentals section of Coddy's Rust journey — lesson 49 of 75.

A method is a sequence of code that has a name. The purpose of a method 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 methods.

To declare a method, we use the following syntax:

fn method_name(parameters) {
	// code
}

For our example, we will create a method named greet and it will look like this:

fn greet() {
    println!("Welcome to Coddy");
}

To use/call/execute the method, we write greet();:

greet();
println!("New session...");
greet();
println!("Another session...");
greet();

This will result in the same output as above.

Convention: It is recommended to declare the method code before its call/execution, as a good practice for readability.

challenge icon

Challenge

Easy

Write a program that gets one input, a number. The input number indicates how many times to execute the below method. 

Create a method that calculates the sum of all of the numbers between 1 and 1000 (including) and prints it, name the method however you like.

Note! As a recommended convention, write the method before its call/execution statements in your code.

Cheat sheet

A method is a sequence of code that has a name, used to reuse code multiple times.

To declare a method:

fn method_name(parameters) {
    // code
}

Example method:

fn greet() {
    println!("Welcome to Coddy");
}

To call/execute a method:

greet();

Convention: It is recommended to declare the method before its call/execution.

Try it yourself

use std::io;

// Method declaration
fn sum_numbers() {
    // Complete Method
    
}


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 method n times
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals