rustHow do I return a variable from a function in Rust?
You can return a variable from a function in Rust by using the return
keyword.
Example code
fn main() {
let x = 5;
let y = add_one(x);
println!("{} + 1 = {}", x, y);
}
fn add_one(x: i32) -> i32 {
return x + 1;
}
Output example
5 + 1 = 6
Code explanation
let x = 5;
- This line declares a variablex
with the value of5
.let y = add_one(x);
- This line calls theadd_one
function with the argumentx
and assigns the return value to the variabley
.fn add_one(x: i32) -> i32 {
- This line declares a functionadd_one
which takes an argumentx
of typei32
and returns a value of typei32
.return x + 1;
- This line returns the value ofx + 1
from theadd_one
function.
Helpful links
Related
- How do I identify unused variables in Rust?
- How do I access a tuple variable by index in Rust?
- How do I get the size of a variable in Rust?
- How do I use a range with a variable in Rust?
- How do I zip variables in Rust?
- How do I reassign a variable in Rust?
- How do I use a variable from another file in Rust?
- How do I create a variable in Rust?
- How do I print the address of a variable in Rust?
- How do I print the type of a variable in Rust?
More of Rust
- Hashshet example in Rust
- How to convert Rust bytes to hex?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to get the last element of a Rust slice?
- How to use non-capturing groups in Rust regex?
- How to use groups in a Rust regex?
- How to match the end of a line in a Rust regex?
- How to escape dots with regex in Rust?
- How to use regex to match a group in Rust?
See more codes...