Functions
Learn how to write and use functions in Rust.
Functions
Functions are the basic building blocks of Rust programs. Every Rust program has at least one function: the main function.
Function Definition
RUSTfn greet() { println!("Hello!"); }
Parameters
RUSTfn greet(name: &str) { println!("Hello, {}!", name); }
Return Value
RUSTfn add(x: i32, y: i32) -> i32 { x + y // No semicolon - this is the return value }
Explicit Return
RUSTfn subtract(x: i32, y: i32) -> i32 { return x - y; // Explicit return (less commonly used) }
Expressions vs Statements
In Rust, there's an important difference between expressions and statements:
- Statement: Performs an action, has no return value
- Expression: Evaluates and returns a value
RUSTlet y = { let x = 3; x + 1 // Expression - no semicolon }; // Statement - has semicolon
Blockchain Functions
In blockchain development, functions are used for:
- Transaction validation: Check if transaction is valid
- Balance calculations: Compute account balances
- Hash generation: Create block and transaction hashes
- Signature verification: Verify transaction signatures
RUSTfn validate_transaction(tx: &Transaction) -> bool { // Validation logic tx.amount > 0 && tx.fee >= MIN_FEE } fn calculate_new_balance(current: u64, amount: u64) -> u64 { current + amount // Expression returns value }
Code Examples
Basic Function
Simple function with parameters and return value
fn main() {
let result = add(5, 3);
println!("5 + 3 = {}", result);
}
fn add(x: i32, y: i32) -> i32 {
x + y
}Explanation:
This is a simple function that adds two integers. The return value is the last expression (without semicolon).
Multiple Parameters
Function with multiple parameters
fn main() {
greet("John", 25);
}
fn greet(name: &str, age: i32) {
println!("Hello, {}! You are {} years old.", name, age);
}Explanation:
Functions can accept multiple parameters. Parameter types must be explicitly specified.
Expressions
The difference between expressions and statements
fn main() {
let x = five();
println!("x value: {}", x);
let y = {
let z = 3;
z + 1
};
println!("y value: {}", y);
}
fn five() -> i32 {
5
}Explanation:
In Rust, expressions (without semicolon) return values. This allows for concise, functional-style code.
Blockchain: Transfer Function
Function for blockchain token transfers
fn transfer_tokens(sender_balance: u64, amount: u64, fee: u64) -> Result<u64, String> {
let total_needed = amount + fee;
if sender_balance < total_needed {
return Err(String::from("Insufficient balance"));
}
let new_balance = sender_balance - total_needed;
Ok(new_balance)
}
fn main() {
let balance = 1000;
match transfer_tokens(balance, 500, 10) {
Ok(new_balance) => println!("Transfer successful! New balance: {}", new_balance),
Err(e) => println!("Transfer failed: {}", e),
}
match transfer_tokens(balance, 1000, 10) {
Ok(new_balance) => println!("New balance: {}", new_balance),
Err(e) => println!("Transfer failed: {}", e),
}
}Explanation:
Blockchain transfer functions validate balances and calculate new balances. They return Result to handle errors like insufficient funds.
Blockchain: Validation Function
Validating blockchain transactions
const MIN_AMOUNT: u64 = 1;
const MIN_FEE: u64 = 10;
fn validate_transaction(amount: u64, fee: u64, sender_balance: u64) -> bool {
if amount < MIN_AMOUNT {
return false;
}
if fee < MIN_FEE {
return false;
}
if sender_balance < amount + fee {
return false;
}
true
}
fn main() {
println!("Valid: {}", validate_transaction(100, 10, 1000));
println!("Invalid (low fee): {}", validate_transaction(100, 5, 1000));
println!("Invalid (insufficient): {}", validate_transaction(1000, 10, 500));
}Explanation:
Validation functions check transaction rules. They return bool to indicate if a transaction is valid. This is critical for blockchain security.
Exercises
Multiplication Function
Write a function that multiplies two numbers and returns the result!
Starter Code:
fn main() {
let result = multiply(4, 5);
println!("4 * 5 = {}", result);
}Text Formatting
Write a function that returns a formatted message!
Starter Code:
fn main() {
let message = create_message("Rust", "fantastic");
println!("{}", message);
}