I have this file hierarchy:
main.rs
protocol/
protocol/mod.rs
protocol/struct.rs
In struct.rs
:
pub struct Struct {
members: i8
}
impl Struct {
pub fn new() -> Struct {
Struct { 4 }
}
}
How do I access it as:
mod protocol;
protocol::Struct::new();
// As opposed to:
// protocol::struct::Struct::new();
I've tried various combinations of pub
use
and mod
but admittedly I'm poking at things blindly.
Is it possible to split a struct (and it's impl
) into a separate file without having to create a new mod?
The short answer: use pub use Type
in your mod.rs
. A full example follows:
My structure:
src/
├── main.rs
├── protocol
│ └── thing.rs
└── protocol.rs
main.rs
mod protocol;
fn main() {
let a = protocol::Thing::new();
println!("Hello, {:?}", a);
}
protocol.rs
pub use self::thing::Thing;
mod thing;
protocol/thing.rs
#[derive(Debug)]
pub struct Thing(i8);
impl Thing {
pub fn new() -> Thing { Thing(4) }
}
As a housekeeping bit, don't call files the same thing as language keywords. struct
causes compilation problems, so I renamed it. Also, your struct creation syntax was incorrect, so I picked the shorter version for this example ^_^.
And to answer the question posed in your title: Without using esoteric features, a file always creates a new module — you can't put something into a different file without also putting it in a different module. You can re-export the type so it doesn't look like it though.
Further explanation: The mod
keyword tells the compiler to look for a file by that name and reference it from the current file as a module. For example, mod protocol;
will look for a file protocol.rs
and behave as if it had included its contents, similar to:
mod protocol {
// ... contents here
};
See Rust by Example for more details.
With mod.rs
:
src/
├── main.rs
└── protocol
├── mod.rs
└── thing.rs
protocol/thing.rs
pub struct Struct {
members: i8
}
impl Struct {
pub fn new() -> Struct {
Struct { members: 4 }
}
}
protocol/mod.rs
pub mod thing;
main.rs
mod protocol;
fn main() {
protocol::thing::Struct::new();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With