Learn Before
Concept

Functions with Return Values - Rust Programming

Functions in Rust can pass back a value to the code that calls them. The type of the returned value needs to be declared after an arrow (->) but it doesn't need a name. The final expression in the function's body is automatically returned unless the return keyword is used to specify a specific value or the function ends early.

For example:

// Way 1: fn add(a: i32, b: i32) -> i32 { return a + b; } // Way 2: fn add(a: i32, b: i32) -> i32 { a + b; // The value of the final expression in the function // body will be implicitly returned as the output } let result = add(3, 4); println!("The result is: {}", result);

In this example, the function add takes two integers, `a` and `b`, as input and returns an integer, which is the sum of `a` and `b`. The function is called with the values `3` and `4` and the result is stored in the variable `result`. The final line then prints "The result is: 7".

0

1

Updated 2024-07-07

References


Tags

Object-Oriented Programming

Programming Language Paradigms

General programming languages

Computing Sciences

Learn After