Rust の基礎

Rust Functions and Return Values

Define functions with typed parameters and return a value without writing return.

  • 初級
  • 約2分で読めます
  • 実行できるサンプル 1 件
学べること
  • Parameters with types
  • Return type after ->
  • The last expression is returned
area(4, 5)
  1. 14, 5arguments
  2. 2width * heightthe body runs
  3. 320returned to the caller

Values go in, one value comes out

A function groups code under a name. In Rust you write the type of every parameter and, after ->, the type of the value the function returns.

The last expression of a function is its return value when it has no semicolon, so width * height is returned without the return keyword. format! builds a String the same way println! prints one.

重要なポイント

  1. Every parameter needs a type.
  2. -> u32 says what the function returns.
  3. A final expression without ; is the return value.

実行できる Rust のサンプル

Rust
コードを実行 →
main.rs
fn area(width: u32, height: u32) -> u32 {
    width * height
}

fn describe(name: &str, size: u32) -> String {
    format!("{name} covers {size} square meters")
}

fn main() {
    let size = area(4, 5);
    println!("{}", describe("The room", size));
}
この例の実行ボタンを作成 実行結果
The room covers 20 square meters

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

次へ: Binary Search →

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ