Rust function
Created By: chatGPT
Rust is a systems programming language that emphasizes safety, concurrency, and performance. To define a function in Rust, you use the
fn
keyword followed by the function name, parameters, and the return type. Below is a simple example of a function that calculates the square of a number.fn square(num: i32) -> i32 {
num * num
}
In this example,
square
takes one parameter, num
, of type i32
(32-bit integer) and returns an i32
result. You can call this function and print the result like this:fn main() {
let result = square(4);
println!("The square of 4 is: {}", result);
}
When you run this program, you will see the output indicating the square of the number you provided. To execute this code, make sure you have the Rust compiler installed. You can use
cargo
, Rust's package manager, to create a new project and run your code.cargo new my_project
cd my_project
// Replace the contents of src/main.rs with your code
cargo run
Moreover, you can also define functions that take multiple parameters. Here’s an example of a function that adds two numbers together:
fn add(a: i32, b: i32) -> i32 {
a + b
}
To call this
add
function, you would do it in a similar way as before:fn main() {
let sum = add(5, 3);
println!("The sum of 5 and 3 is: {}", sum);
}