首页 > 编程语言 > 详细

Rust语言学习笔记(5)

时间:2018-08-12 12:54:38      阅读:308      评论:0      收藏:0      [点我收藏+]

Structs(结构体)

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}
let mut user1 = User {
    email: String::from("someone@example.com"),
    username: String::from("someusername123"),
    active: true,
    sign_in_count: 1,
};
user1.email = String::from("anotheremail@example.com");
// 结构体初始化缩写形式
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("another@example.com"),
    username: String::from("anotherusername567"),
    ..user1 // active: user1.active, ...
};

Tuple Structs(元组结构体)

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
}
*/

方法

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}
impl Rectangle {
    fn square(size: u32) -> Rectangle {
        Rectangle { width: size, height: size }
    }
}
fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };
    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );

    let rect2 = Rectangle { width: 10, height: 40 };
    let rect3 = Rectangle { width: 60, height: 45 };
    println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
    println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));

    let sq = Rectangle::square(3);
}
/*
The area of the rectangle is 1500 square pixels.
Can rect1 hold rect2? true
Can rect1 hold rect3? false
*/
  • 定义方法采用 impl 关键字。方法在结构体之外的 impl 块中定义。
  • 方法签名中指向结构体自身的参数有3种形式:self, &self, &mut self。
  • self 参数不需要标注类型。
  • 调用方法采用 object.method() 语法。
    object 形式固定,无论方法签名中的 self 参数采用何种形式。
  • 同一个结构体的方法可以定义在多个 impl 块中。
  • impl 块中可以定义不带 self 参数的函数。这些函数通常用作构造器。

Rust语言学习笔记(5)

原文:https://www.cnblogs.com/zwvista/p/9462355.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!