Rust Book 4,5 章

4章

特になし。

5章

Defining and Instantiating Structs

引数と field の名前が同じ場合、下記のようにかける。

fn build_user(email: String, username: String) -> User {
    User {
        email,
        username,
        active: true,
        sign_in_count: 1,
    }
}

.. シンタックスを使えば、他のインスタンスと同じ値を代入したい場合、簡潔にかける。

let user2 = User {
    email: String::from("another@example.com"),
    username: String::from("anotherusername567"),
    ..user1
};

この辺は知らなかったけど、前からあったのかな?

An Example Program Using Structs

この辺は特に目新しいものはなかった。

Method Syntax

imple ブロックは同じものを複数かける。

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

書かないけど。

Contents

comments powered by Disqus