Rust: Using Structs to Structure Related Data

Using Structs to Structure Related Data

Defining and Instantiating Structs

格式

struct Data_name {
    data1: type1,
    data2: type2,
}// 注意无;
struct Data {
    name: String,
    age: u32,
    gender: bool,
    balance: f32,
}

初始化一个 struct 对象

let user = Data {
    name: String::from("SCUT"),
    age: 1900,
    gender: true,
    balance: 0.0,
};

访问对象中的元素

println!("{} {} {} {}", user.name, user.age, user.gender, user.balance);

.. 语句

let user1 = Data {
    name: String:: from("SCUT"),
    gender: false,
    ..user // # 末尾无,
};

这样创建出来的 user1 ,未指出的变量会复制 user 中的,注意会有 move 语句,所有权可能会变化

let user1 = Data {
    name: String:: from("SCUT"),
    gender: false,
    ..user // # 末尾无,
};
println!("{} {} {} {}", user1.name, user1.age, user1.gender, user1.balance);

// value borrowed here after move !! !! !!
let user2 = Data {
    ..user
};

println!("{} {} {} {}", user2.name, user2.age, user2.gender, user2.balance);
// println!("{} {} {} {}", user.name, user.age, user.gender, user.balance);// Error! value borrowed here after move

tuple struct

格式

struct Data_name(type1, type2,...); // 有;

创建对象

// tuple struct
struct Point(f32, f32);
let p = Point(0.0, 0.0);

访问元素

println!("{} {}", p.0, p.1);// 看成元组访问

An Example Program Using Structs

debug

在类前面加 #[derive(Debug)]

#[derive(Debug)]
struct Data {
    name: String,
    age: u32,
    gender: bool,
    balance: f32,
}

输出 类

{:?} 语法

println!("{:?}", user);
// output
// Data { name: "SCUT", age: 1900, gender: true, balance: 0.0 }

{:#?} 语法

println!("{:#?}", user);
// output
/*
    Data {
        name: "SCUT",
        age: 1900,
        gender: true,
        balance: 0.0,
    }
*/

格式不同

作为参数

struct Rectangle {
    width: f64,
    height: f64,
}// 定义一个 rect

fn area(rect: &Rectangle) -> f64 {
    rect.width * rect.height
}

let rect = Rectangle {
    width: 3.1,
    height: 4.1,
};
println!("{}", area(&rect));// 12.709999999999999 精度

Method Syntax

实现类中的函数

impl 语句 implementations

格式

impl srtuct_name {
    fn func1(&self, ...) {
        
    }
    
    fn func2(...) {// 无 &self 为关联函数 通过 类名::func2() 调用
        
    }
}

例如

#[derive(Debug)]
struct Rectangle {
    width: f64,
    height: f64,
}

impl Rectangle {
    fn area(&self) -> f64 {
        self.width * self.height
    }

    fn hold(&self, rect: &Rectangle) -> bool {
        self.width >= rect.width && self.height >= rect.height
    }

    // 关联函数 无self
    fn square(size: f64) -> Rectangle {
        Rectangle {
            width: size,
            height: size,
        }
    }
}

let r1 = Rectangle {
    width: 10.0,
    height: 20.0,
};

let r2 = Rectangle {
    width: 11.0,
    height: 21.0,
};

println!("{} {}", r1.hold(&r2), r2.hold(&r1));

let sq = Rectangle::square(10.0);
println!("{:#?}", sq);

以上就是 Ruststruct