LoginSignup
1
0

More than 3 years have passed since last update.

Rustの関数について

Posted at

まえがき

この記事はRUSTチュートリアルをZerobillbank社内メンバー(有志)で勉強がてら、可能な限りわかりやすく内容を書き出す企画の一部です。

なお、初学者のため(略)という免責を打ちつつ間違いなどあればコメントで教えていただけますと一同嬉しく思います!

本項は関数について記載します。
https://doc.rust-jp.rs/book/second-edition/ch03-03-how-functions-work.html

関数の動作法

関数の命名規則

Rustの関数と変数の命名規則は、スネークケースを使うのが慣例です。

fn my_function() {
    println!("My Function.");
}

関数の引数

関数定義では引数の型注釈が必須です。

fn my_function(x: i32) {
    println!("The value of x is: {}", x);
}

戻り値のある関数

"->"の後に型を書きます。

fn five() -> i32 {
    5
}

上記の関数では"return"が記述されていません。
Rustではブロックの最後の式の値が暗黙的に返却されるため、"return"の記述が必要ありません。

"return"で戻り値の値を指定することもできますが、上記の書き方が一般的なようです。

また、下記のように5の後ろにセミコロンを付けたらどうなるでしょう?

fn five() -> i32 {
    5;
}

error[E0308]: mismatched types
 --> src/main.rs:6:14
  |
6 | fn five() -> i32 {
  |    ----      ^^^ expected `i32`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail or `return` expression
7 |     5;
  |      - 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 `playground`.

To learn more, run the command again with --verbose.

上記のようなエラーになります。
行末にセミコロンを付けた場合に式は文に変換され、値を返却しなくなることが原因です。

では、式と文とはどういうものでしょう?

    • なんらかの動作をして値を返さない命令
    • 結果が値に評価される

文の例

let y = 6;  // let y = 6; はyに6を代入している。結果として値を返さない命令となる

式の例

{
    let x = 3;
    x + 1 // 式となり4を返す
}

このように、他の言語だとあまり見られない;の使い分けがあるので注意が必要です。

さいごに

ZEROBILLBANKでは一緒に働く仲間を募集中です。
ZEROBILLBANK JAPAN Inc.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0