你能把 struct impl 块放在不同的文件中吗?
Can you put struct impl blocks in a different file?
假设您有三个文件:main.rs
、struct.rs
和 impl.rs
。你可以在 struct.rs
中定义一个结构,在其中放置一个 impl
,在 impl.rs
中放置另一个 impl
,然后使用来自 [=] 的两组 impl
11=]?如果可以,怎么做?
项目结构:
main.rs:
use struct;
use impl;
main() {
let foobar = struct::Struct::new(); // defined in struct.rs
foobar.x(); // defined in impl.rs
}
struct.rs:
Define Struct, first impl
impl.rs:
Second impl
是的,这是可能的。您可以在整个板条箱中为您的结构提供实现。您只是不能为来自外国板条箱的类型提供 impls。而且您不需要做任何特别的事情来完成这项工作——只需确保该结构在 main
中可见。当然,您不能将模块命名为 struct
和 impl
,因为这些是保留字。
下面是一些示例代码:
fn main() {
use struct_::A;
A::foo();
A::bar();
}
pub mod struct_ {
pub struct A;
impl A {
pub fn foo() {}
}
}
mod impl_ {
impl crate::struct_::A {
pub fn bar() {}
}
}
假设您有三个文件:main.rs
、struct.rs
和 impl.rs
。你可以在 struct.rs
中定义一个结构,在其中放置一个 impl
,在 impl.rs
中放置另一个 impl
,然后使用来自 [=] 的两组 impl
11=]?如果可以,怎么做?
项目结构:
main.rs:
use struct;
use impl;
main() {
let foobar = struct::Struct::new(); // defined in struct.rs
foobar.x(); // defined in impl.rs
}
struct.rs:
Define Struct, first impl
impl.rs:
Second impl
是的,这是可能的。您可以在整个板条箱中为您的结构提供实现。您只是不能为来自外国板条箱的类型提供 impls。而且您不需要做任何特别的事情来完成这项工作——只需确保该结构在 main
中可见。当然,您不能将模块命名为 struct
和 impl
,因为这些是保留字。
下面是一些示例代码:
fn main() {
use struct_::A;
A::foo();
A::bar();
}
pub mod struct_ {
pub struct A;
impl A {
pub fn foo() {}
}
}
mod impl_ {
impl crate::struct_::A {
pub fn bar() {}
}
}