day 18 @rust 構造体

・基本構文

struct User {
    name: String,
    email: String,
    age: u8,
}

・構造体の使用

let user = User {
    email: String::from("Taro"), // 順番は関係ない。
    name: String::from("hoge@hoge.com"),
    age: 10,
};

let user_name = user.name;

・フィールド名の省略
変数名が同じなら省略できる。

fn main() {
    let name = String::from("Taro");
    let age = 10;
    let email = String::from("hoge@hoge.com");
    let user = User {
        name,
        age,
        email,
    };
}


・更新構文

let user2 = User {
    name: String::from("Taro"),
    email: String::from("hoge@gmail.com"),
    ..user1
}

・タプル構造体
タプルに別名をつけるのに使う。
対象のタプルが同じであれば別の型になる

    struct Color(i32, i32, i32);
    struct Position(i32, i32, i32);
    
    let color = Color(0, 0, 0);
    let mut pos = Position(0, 0, 0);

    let color = pos; //タプルの型は同じだが併用はできない。

・ユニットライクな構造体
関数を集めるのに使う。