Rust 程式語言中的函式
函式是程式碼的構建塊。它們使我們能夠避免編寫類似的程式碼,並有助於將大段程式碼組織成可重用的元件。
在 Rust 中,函式隨處可見。甚至函式定義也是 Rust 中的語句。
Rust 中最重要的函式之一是 main 函式,它是任何軟體或應用程式的入口點。
我們在 Rust 中使用 fn 關鍵字來宣告函式。
在 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()! 宏列印該值。
需要注意的是,如果我們將函式 sample 從表示式更改為語句,則 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`發生這種情況是因為函式 sample 預期返回一個 i32 值,但在其內部,存在一個不計算為值的語句,因此與函式宣告相矛盾。只需刪除分號即可將語句轉換為表示式,程式碼將正常工作。
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP