严格来说,您不能将一个模块拆分为不同的文件,但您不需要这样做,因为您可以将子模块定义为类似的效果(这也是一个更好的解决方案)。
你可以像这样安排你的模块:
src/app.rs
src/logging/mod.rs // parent modules go into their own folder
src/logging/logger.rs // child modules can stay with their parent
src/logging/sql.rs
这是文件的样子
src/app.rs
mod logging;
pub struct App;
fn main() {
let a = logging::Logger; // Ok
let b = logging::Sql; // Error: didn't re-export Sql
}
src/logging/mod.rs
// `pub use ` re-exports these names
// This allows app.rs or other modules to import them.
pub use self::logger::{Logger, LoggerTrait};
use self::sql::{Sql, SqlTrait};
use super::App; // imports App from the parent.
mod logger;
mod sql;
fn test() {
let a = Logger; // Ok
let b = Sql; // Ok
}
struct Foo;
// Ok
impl SqlTrait for Foo {
fn sql(&mut self, what: &str) {}
}
src/logging/logger.rs
pub struct Logger;
pub trait LoggerTrait {
fn log(&mut self, &str);
}
src/logging/sql.rs
pub struct Sql;
pub trait SqlTrait {
fn sql(&mut self, &str);
}