有没有什么方法可以直接从rust中的不同文件夹导入struct

gojuced7  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(171)

这是我的文件夹结构

├── main.rs
├── structs
│   ├── mod.rs
│   ├── student.rs
│   └── date.rs

这是所有文件中的代码
structs/mod.rs

pub mod date;
pub mod student;

structs/date.rs

pub struct Date {
    pub day: i8,
    pub month: i8,
    pub year: i16,
}

impl Date {
    pub fn new(day: i8, month: i8, year: i16) -> Date {
        return Date {
            day,
            month,
            year
        };
    }
}

structs/student.rs

use crate::structs::date::Date;

pub struct Student {
    pub name: String,
    pub age: i32,
    pub email: String,
    pub dob: Date,
}

impl Student {
    pub fn new(name: &str, age: i32, email: &str, dob: Date) -> Student {
        return Student {
            name: String::from(name),
            age,
            email: String::from(email),
            dob,
        };
    }
}

main.rs

mod structs;

fn main() {
    let mut students = Vec::<structs::student::Student>::new();

    students.push(
        structs::student::Student::new(
            "Sahil Verma",
            21,
            "sahil@gmail.com",
            structs::date::Date::new(3, 9, 2001),
        )
    );
}

现在,我只想写入Date,而不是写入整个structs::date::Date,对于structs::student::Student也是如此。
那么,我能得到一些如何做的许可,或者什么是最好的方式来安排文件夹,使模块得到自动导入

zrfyljdw

zrfyljdw1#

使用use语句导入它们:

mod structs;

use structs::{date::Date, student::Student};

fn main() {
    let mut students = Vec::<Student>::new();

    students.push(
        Student::new(
            "Sahil Verma",
            21,
            "sahil@gmail.com",
            Date::new(3, 9, 2001),
        )
    );
}

相关问题