Rust语言学习笔记(5)

结构体

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}
let mut user1 = User {
    email: String::from("[email protected]"),
    username: String::from("someusername123"),
    active: true,
    sign_in_count: 1,
};
user1.email = String::from("[email protected]");
// 结构体初始化缩写形式
fn build_user(email: String, username: String) -> User {
    User {
        email, // email: email,
        username, // username: username,
        active: true,
        sign_in_count: 1,
    }
}
// 结构体更新语法
let user2 = User {
    email: String::from("[email protected]"),
    username: String::from("anotherusername567"),
    ..user1 // active: user1.active, ...
};

元组结构体(tuple constructs)

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
  • 元组结构体实质上是整体有名字但是成员没有名字的元组。
  • 成员完全相同但是结构体名字不同的两个元组结构体不是同一个类型。
    比如 Color 和 Point 是两个类型。
  • 可以定义完全没有成员的单元元组结构体。

Debug 特质

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };
    println!("rect1 is {:?}", &rect1);
    println!("rect1 is {:#?}", &rect1);
}
/*
rect1 is Rectangle { width: 30, height: 50 }
rect1 is Rectangle {
    width: 30,
    height: 50
}
*/

猜你喜欢

转载自www.cnblogs.com/zwvista/p/9462355.html