Member-only story

Mastering Rust Functions: A Beginner’s Guide to Efficient Code

In this lesson, we will dive into Rust functions, including syntax, closures, higher-order functions, and best practices for writing efficient, clean, and reusable code.

Uday Hiwarale
rustycrab
21 min read6 days ago

At this point, we are already somewhat familiar with functions. Since we need to use the main function, which is the entry point of a Rust program, and we have seen a couple of examples in previous lessons, we understand how a function in Rust looks. However, in this lesson, we are going to learn the ins and outs of functions.

Functions

fn say_hello() {
println!("Hello, world!");
}

fn main() {
say_hello();
}

// Hello, world!

We define a function in Rust using the keyword fn, followed by the name of the function. Like variables, the function name follows the same convention: it should be in snake_case, such as say_hello in the example above.

fn say_hello(name: &str) {
println!("Hello, {}!", name);
}

fn main() {
say_hello("John");
}

// Hello, John!

If we want to pass data to a function, we can do so using function arguments. These need to be specified in parentheses () along with their data types. If a function…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

rustycrab
rustycrab

Published in rustycrab

Join me on a journey to explore Rust programming! I’ll break down complex concepts into simple, easy-to-understand articles, making Rust approachable for everyone. Whether you’re new or experienced, let’s learn and grow together in the world of Rust!

No responses yet

Write a response