[rust]结构体

100 阅读2分钟

定义一个结构体

  1. 可以定义一个有成员变量的结构体
  2. 也可以定义一个空结构体
struct User {
    id: i64,
    user_name: String,
    age: i8,
    is_health: bool,
}


struct Empty{}

创建结构体实例的三种方式

  1. 创建不可变结构体(参数内容不可变)
  2. 创建可变结构体(参数内容可修改)
  3. 参数名字和字段名相同可简写
  4. 可以从其他结构体创建实例(必须是同一种结构类型)
fn main() {
    // 1. 创建结构体实例,默认不可变
    let jack = User {
        id: 1,
        user_name: "jack".to_string(),
        age: 18,
        is_health: true,
    };

    // 2. 创建可变结构体实例
    let mut jack = User {
        id: 1,
        user_name: "Jack".to_string(),
        age: 18,
        is_health: true,
    };

    // 修改结构体字段
    jack.user_name = String::from("Tom");

    // 3.字段简写
    let age = 19;
    let user_name = String::from("Micky");
    let micky = User {
        id: 1,
        user_name, // 简写
        age, // 简写
        is_health: true,
    };

    // 4. ***********从其他结构体创建***************

    // 4.1 全部从其他结构体创建
    let tom = User {
        ..micky
    };
    println!("tom's real name: {}", tom.user_name); // Micky

    // 4.2 部分从其他结构体创建
    let jin = User {
        id: 20,
        user_name: "Jin".to_string(),
        ..tom
    };
    println!("jin's age: {}", jin.age); // 19
    println!("jin's health: {}", jin.is_health) // true
}

元组结构体

  1. 字段没有名称
  2. 圆括号(自定义结构体是方括号)
  3. 访问元组结构体字段使用点+下标访问
fn main() {
    let tom = (1, "Tom".to_string(), 20, true);

    println!("tom.id = {}",tom.0);
    println!("tom.name = {}",tom.1);
    println!("tom.age = {}",tom.2);
    println!("tom.health = {}",tom.3);
}

打印结构体

#[derive(Debug)] // 标识:Rust标准打印
struct User {
    id: i64,
    user_name: String,
    age: i8,
    is_health: bool,
}

fn main() {
    let tom = User{
        id: 1,
        user_name: "".to_string(),
        age: 18,
        is_health: true,
    };
    println!("{:?}",tom); // 标准打印
    println!("{:#?}",tom); // 标准格式化打印
}

序列化结构体

Cargo.toml

serde = { version = "1.0.210", features = ["derive"] }
serde_json = "1.0.128"
pub struct ConversationInfo {
    conversation_short_id: i64,
    conversation_id: String,
}


#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_serde() {
        let info = ConversationInfo { conversation_short_id: 123, conversation_id: "0:1:123:456".to_string() };
        let info_str = serde_json::to_string(&info).unwrap(); // 序列化为JSON字符串
        println!("{:#?}", info);
        println!("{}", info_str);

        let conv_info: ConversationInfo = serde_json::from_str(&info_str).unwrap(); // 反序列化
        println!("{:#?}", conv_info); // 标准打印
    }
}

// 输出
// ConversationInfo {
// conversation_short_id: 123,
// conversation_id: "0:1:123:456",
// }
// {"conversation_short_id":123,"conversation_id":"0:1:123:456"}
// ConversationInfo {
// conversation_short_id: 123,
// conversation_id: "0:1:123:456",
// }