【Rust】结构体 struct

定义结构体

#[derive(Debug)]
struct Rectangle {
    name: String,
     u32,
    height: u32,
}

定义结构体方法

impl Rectangle {
    // 方法
    fn area(&self) -> u32 {
        self.width * self.height
    }
    // 更多参数的方法
    fn hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
    // 关联函数
    fn square(size: u32) -> Rectangle {
        Rectangle { name: String::from(""),  size, height: size }
    }
}

impl 是 implementation 的缩写。

Self 类型是 impl 块的类型的别名。方法的第一个参数必须有一个名为 self 的 Self 类型的参数。&self 实际上是 self: &Self 的缩写,表示方法借用了 Self 实例。

如果想要在方法中改变调用方法的实例,需要将第一个参数改为 &mut self

更过参数的方法,参数必须放在第二个

关联函数(associated functions),定义不以 self 为第一参数的关联函数(因此不是方法),因为它们并不作用于一个结构体的实例。

结构体使用

let rectangle = Rectangle { name: String::from("R"),  10, height: 20 };
println!("{:?}", rectangle);
println!("The area of the rectangle {} is {}", rectangle.name, rectangle.area());

字段初始化简写语法(field init shorthand)

let rectangle1 = build_rectangle(String::from("R1"), 10, 20);
println!("{:?}", rectangle1);
println!("The area of the rectangle {} is {}", rectangle1.name, rectangle1.area());

fn build_rectangle(name: String,  u32, h: u32) -> Rectangle {
    Rectangle {name,width,height:h}
}

参数与结构体字段同名时,仅写一个名称就可以,不用写成 key: value 形式。

结构体更新语法(struct update syntax)

let rectangle2 = Rectangle {name: String::from("R2"),..rectangle1};
println!("{:?}", rectangle2);
println!("The area of the rectangle {} is {}", rectangle2.name, rectangle2.area());

.. 语法指定了剩余未显式设置值的字段应与给定实例对应字段相同的值

元组结构体(tuple structs)

struct Color(i32, i32, i32);
let black = Color(0, 0, 0);

使用没有命名字段的元组结构体来创建不同的类型,元组结构体有着结构体名称提供的含义,但没有具体的字段名,只有字段的类型。

类单元结构体(unit-like structs)

struct AlwaysEqual;
let subject = AlwaysEqual;

没有任何字段的类单元结构体

原文地址:https://www.cnblogs.com/yangchongxing/p/15799687.html