乐闻世界logo
搜索文章和话题

How can you define a function in Rust, and what is the return type of a function?

1个答案

1

Defining functions in Rust typically follows the following syntax structure:

rust
fn function_name(parameter: type, ...) -> return_type { // function body }

Key elements of function definition:

  1. fn keyword: Used to declare a new function.
  2. Function name: In Rust, function names typically follow snake_case convention (using lowercase letters and underscores).
  3. Parameters: Specify the inputs the function accepts; each parameter must have type annotations.
  4. Return type: Specified using the arrow -> and the type name. If not explicitly specified, it defaults to (), the empty tuple, similar to void in other languages.

Example:

Suppose we want to write a function that accepts two integer parameters and returns their sum:

rust
fn 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:

rust
fn 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 回复

你的答案