【问题标题】:Can you put struct impl blocks in a different file?您可以将 struct impl 块放在不同的文件中吗?
【发布时间】:2021-10-08 10:53:14
【问题描述】:

假设您有三个文件:main.rsstruct.rsimpl.rs。您能否在struct.rs 中定义一个结构,在其中放置一个impl,在impl.rs 中放置另一个impl,然后使用main.rs 中的两组impls?如果有,怎么做?

项目结构:

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

【问题讨论】:

    标签: struct rust project-structure


    【解决方案1】:

    是的,这是可能的。您可以在整个 crate 中为您的结构提供实现。您只是不能为来自外国箱子的类型提供 impls。你不需要做任何特别的事情来完成这项工作——只要确保结构在main 中可见。当然,您不能将模块命名为 structimpl,因为它们是保留字。

    下面是一些示例代码:

    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() {}
        }
    }
    

    (Playground)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 2023-01-22
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      相关资源
      最近更新 更多