-
Book Overview & Buying
-
Table Of Contents
The Rust Programming Handbook
By :
In this final section of the chapter, we’ll explore functions, a fundamental building block of Rust programs. Functions allow you to encapsulate and reuse logic throughout your code, making it more modular and easier to maintain. Defining and using functions is essential for writing effective Rust programs.
Functions in Rust are defined using the fn keyword, followed by the function name, parameters, and the function body. Let’s define a simple function to see how it works.
In Rust, functions can be defined globally (outside main) or locally (inside another function). This example shows both approaches:
// Global function (available everywhere)
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
// Local function (only available inside main)
fn greet(name: &str) {
println!("Hello, {}!", name);
}
// Call the local function
greet("Alice");
greet("Bob");
// Call the global function
let sum = add(1, 2);
println!("The sum is: {}", sum);
}
In this example, we see both the function definition and the function invocation:
greet function takes a single parameter name of the &str type (a string slice), and prints a greeting message. This demonstrates how to define a function and use parameters.add function takes two parameters (a and b) of the i32 type (32-bit integers) and returns their sum. This demonstrates how to define a function that returns a value.greet function twice with different arguments ("Alice" and "Bob"), demonstrating how to pass arguments to functions.add function with arguments of 5 and 7, store the result in the variable sum, and print it.These are just a few of the core syntax concepts in Rust. In this chapter, we’ve introduced the basics of Rust programming, including variables and mutability, data types, control flow, and functions. Each of these topics is crucial for building a solid foundation in Rust.
As we progress through the book, we’ll explore more advanced topics and dive deeper into Rust’s syntax and features. Each chapter will provide detailed explanations, practical examples, questions, and assignments to help you master Rust programming. By the end of this book, you’ll have a comprehensive understanding of Rust and be well equipped to tackle complex programming challenges confidently.