1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rust言語の勉強を初めてみた。その4

Posted at

Functions

https://doc.rust-lang.org/book/ch03-03-how-functions-work.html

mainがプログラムの最初に実行される関数。
Rustの関数名はスネークケース(すべて小文字で、単語を"_"で区切る)が一般的。

fn main() {
    println!("Hello, world!");

    another_function();
}

fn another_function() {
    println!("Another function.");
}

関数はfnで始まり、関数名の後に()をつける。{}の中は関数本体を表す。
定義した関数は関数名()で呼び出す。

Function Parameters

関数には引数を持たせることができる。

fn main() {
    another_function(5);
}

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

引数には型注釈が必要。

カンマ区切りで引数を複数持たせることができる。

fn main() {
    another_function(5, 6);
}

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

Function Bodies Contain Statements and Expressions

ステートメントは、値を返さないアクション。

fn main() {
    let x = (let y = 6);
}

let y = 6はステートメントで値を返さないため、xには値は入らない(ビルドエラー)

fn main() {
    let x = 5;

    let y = {
        let x = 3;
        x + 1
    };

    println!("The value of y is: {}", y);
}

x+1には;が無いため、

    {
        let x = 3;
        x + 1
    };

の部分が一つの式となり、その式を評価した結果(4)がyに入る。

Functions with Return Values

関数は値を返すことが出来る。
矢印(->)の後に型を付ける。
関数の戻り値は関数本体のブロック内の最終式の値となる。
returnで任意の位置で戻ることも出来る。

fn five() -> i32 {
    5
}

fn main() {
    let x = five();

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

five()には5という数字しか無いが、Rustでは有効な関数。
five()はi32型の5という数字が返る。
これは

let x = 5;

と同じ。

fn main() {
    let x = plus_one(5);

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

fn plus_one(x: i32) -> i32 {
    x + 1
}

これは The value of x is: 6と出力される。
しかし、x + 1;と書くと、ビルドエラーとなる。
関数の戻り値の型がi32と示されているのに対し、ステートメント(x + 1;)は値を返さないため、型の不一致となる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?