# 定义

struct User {
    name: String,
    age: usize,
    gender: u8
}

# 使用

let mut user = User {
    name: String::from("Cecil"),
    age: 26,
    gender: b'M'
};

# 简化

fn build_user(name: String, user: User) -> User {
    User {
        name,
        ..user
    }
}

name 要和字段同名才可以,否则还是得 name: name1

# 元组结构体

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

# 类单元结构体

struct Unit();
let unit = Unit();

# 结构体的所有权

结构体内,定义需要自身所有权;例如 String,不能是 &str 的 slice 类型

否则拥有其它对象的引用会编译错误,除非加上生命周期。后面章节讲。

结构体是为了组织代码。面向对象的思想。

但是直接打印,会报错

fn main() {
    let rectangle = Rectangle {
        width: 10,
        height: 10
    };
    println!("{}", rectangle);
}
struct Rectangle {
    width: u32,
    height: u32
}

改进,需要实现 Display 和 Debug trait

fn main() {
    let rectangle = Rectangle {
        width: 10,
        height: 10
    };
    println!("{:#?}", rectangle);
}
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32
}

# 方法与结构体紧密联系

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}
// 创建 rectangle
// rectangle.area();

&self 和 &Retangle 类似,仅仅获取引用,不获取所有权。

如果想修改则使用 &mut self

# -> 运算符去哪了?

其它语言,如果是指针,需要这样用:obj->something (),或者 (*obj).something ();

Rust 会自动引用和解引用

p1.something(&p2);
// 等效
(&p1).something(&p2);

# 方法不带 &self ?

不带的话,还是称为函数,使用时,使用::符号,例如:String::from ("");

fn main() {
    // 类似 Java 的静态方法
    let rectangle = Rectangle::rectangle(10);
    println!("{}", rectangle.area());
}
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32
}
impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
    // 不带 &self
    fn rectangle(size: u32) -> Rectangle {
        Rectangle {
            width: size,
            height: size
        }
    }
}

# 多个 impl 块

支持多个 impl 块定义

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

不过还是建议放在一起,除非和 trait 配合使用

更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Cecil 微信支付

微信支付

Cecil 支付宝

支付宝

Cecil PayPal

PayPal