0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rust | 構造体を理解すると、かけるコードの幅が広がるよ。

0
Posted at

本記事ではRustにおける構造体について説明します。

構造体とは?

構造体とは、異なるデータ型の複数の項目をひとまとめにした新しいデータ型です。

Rustで書いてみよう!

Rustで構造体を定義するには、structという宣言を使います。
形として、struct {構造体の名前}{}です。

struct User {
    name:String,
    age:usize,
    active:bool,
}

これで一つのができました。

作った型を使う。

一個前で定義した構造体を変数で定義してみましょう。

let user = User {
    name:String::from("Kanade"),
    age:15,
    active:true,
};

これは、userという変数がUserという型の名の下に定義されました。

関数の返り値

structで定義した構造体はなので、関数の返り値に指定できます。

fn create()-> User {
    User {
        name:string::from("Kanade"),
        age:15,
        active:true,
    }
}

これは、 『Rustらしい書き方』なので、他の言語と同様、変数に構造体を定義して、それを返り値として書くことも可能です。

fn create()-> User {
    let user = User {
        name:string::from("kanade"),
        age:15,
        active:true,
    };
    user
}
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?