Rust 编程语言中的函数

rust programmingserver side programmingprogramming

函数是代码的构建块。它们使我们避免编写类似的代码,还有助于将大量代码组织成可重用的组件。

在 Rust 中,函数随处可见。甚至函数定义在 Rust 中也是语句。

Rust 中最重要的函数之一是 main 函数,它是任何软件或应用程序的入口点。

我们使用 fn 关键字在 Rust 中声明函数。

在 Rust 中,函数名称使用蛇形命名法作为常规样式。在蛇形命名法中,单词的所有字母都小写,并使用 _(下划线)分隔两个单词。

考虑一个简单的函数,我们在其中打印"Hello, Tuts!"

文件名:src/main.rs

示例

fn main() {
   println!("Hello, Tuts!");
}

输出

上述代码的输出为 −

Hello, Tuts!

在上述代码片段中,函数定义以 fn 关键字开头,函数名称后跟一对括号。花括号是函数体的一部分,它们告诉编译器函数体从哪里开始,在哪里结束。

调用另一个函数

在 Rust 中调用/调用函数与其同类语言类似。我们只需要输入其名称,后跟括号。

以以下代码片段为例。

文件名:src/main.rs

示例

fn main() {
   sample();
   println!("Hello, Tuts!");
}
fn sample(){
   println!("another function”);
}

输出

上述代码的输出为 −

   Compiling hello-tutorialspoint v0.1.0 (/Users/immukul/hello-tutorialspoint)
   Finished dev [unoptimized + debuginfo] target(s) in 1.04s
   Running `target/debug/hello-tutorialspoint`
another function
Hello, Tuts!

Rust 并不关心您在哪里定义正在调用的函数,唯一重要的是它应该被定义。

函数参数

参数是我们在定义函数时放在括号内的值。它们是函数签名的一部分。

让我们稍微修改一下上面的例子,并将一个参数传递给我们正在调用的函数,看看它是如何工作的。

文件名:src/main.rs

示例

fn main() {
   sample(5);
   println!("Hello, Tuts!");
}
fn sample(x : i32){
   println!("The value of x is : {} ", x);
}

输出

   Finished dev [unoptimized + debuginfo] target(s) in 0.01s
   Running `target/debug/hello-tutorialspoint`
The value of x is : 5
Hello, Tuts!

我们通过调用sample(5)来调用该函数;该函数又调用具有名为x的参数的sample函数。参数x被分配为i32类型。然后println()!宏打印此参数的值。

需要注意的是,如果函数括号中定义了多个参数,则所有这些参数都必须声明类型。

请参考以下代码片段。

文件名:src/main.rs

示例

fn main() {
   sample(5,7);
   println!("Hello, Tuts!");
}
fn sample(x : i32, y : i32){
   println!("The value of x is : {} ", x);
   println!("The value of y is : {} ", y);
}

输出

   Compiling hello-tutorialspoint v0.1.0 (/Users/immukul/hello-tutorialspoint)
   Finished dev [unoptimized + debuginfo] target(s) in 0.51s
   Running `target/debug/hello-tutorialspoint`
The value of x is : 5
The value of y is : 7
Hello, Tuts

带返回值的函数

函数可以向调用函数返回值。这是函数的一个非常常见的用例。

文件名:src/main.rs

fn main() {
   let z = sample(5);
   println!("Output is: {}",z);
}
fn sample(x : i32) -> i32{
   x + 1
}

调用函数 sample 并传递 5 作为参数,然后将该函数的返回值存储到名为 z 的变量中,最后使用 println()! 打印该值Marco。

需要注意的是,如果我们将函数示例从表达式更改为语句,那么 Rust 编译器将抛出编译错误。

文件名:src/main.rs

示例

fn main() {
   let z = sample(5);
   println!("Output is: {}",z);
}
fn sample(x : i32) -> i32{
   x + 1;
}

输出

Compiling hello-tutorialspoint v0.1.0 (/Users/immukul/hello-tutorialspoint)
error[E0308]: mismatched types
--> src/main.rs:6:23
|
6 | fn sample(x : i32) -> i32{
| ------ ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
7 | x + 1;
| - help: consider removing this semicolon
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
error: could not compile `hello-tutorialspoint`

发生这种情况的原因是,函数示例预计会返回一个 i32 值,但其中存在一个不计算值的语句,因此与函数声明相矛盾。只需删除分号以将语句转换为表达式,代码就可以正常工作。


相关文章