Defining functions in Rust typically follows the following syntax structure:
rustfn function_name(parameter: type, ...) -> return_type { // function body }
Key elements of function definition:
fnkeyword: Used to declare a new function.- Function name: In Rust, function names typically follow snake_case convention (using lowercase letters and underscores).
- Parameters: Specify the inputs the function accepts; each parameter must have type annotations.
- Return type: Specified using the arrow
->and the type name. If not explicitly specified, it defaults to(), the empty tuple, similar tovoidin other languages.
Example:
Suppose we want to write a function that accepts two integer parameters and returns their sum:
rustfn add_two_numbers(a: i32, b: i32) -> i32 { a + b }
This add_two_numbers function accepts two i32 integers as parameters and returns an i32 integer, which is the sum of the two integers.
Functions with no return value:
If a function does not need to return any value, you can omit the return type or use () to indicate it. For example, a function that prints a welcome message might look like this:
rustfn print_welcome_message() { println!("Welcome to our program!"); }
In this example, the print_welcome_message function accepts no parameters and has no return value. In Rust, this is considered to return the () type.
By following these basic rules and examples, you can flexibly define various functional functions in Rust.
2024年8月7日 14:44 回复