You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中如何导入模块全部内容但排除指定项?

Rust 导入模块所有内容但排除指定项的实现方法

为了方便,我在代码里大量使用重导出,但有时候需要特意排除某些项,避免命名混淆或实现冲突。我有Scala背景,原本以为下面这段代码无法编译(我也希望它编译失败),因为Bar as _语法应该会在导入时丢弃Bar,但它居然能正常编译。有没有Rust语法能实现我想要的效果?

pub mod stuff{
    pub struct Foo{}
    pub struct Bar{}
}

pub mod other_stuff{
    use super::stuff::{*, Bar as _};
    pub struct Baz{
        foo : Foo,
        bar : Bar
    }
}

明确需求:我想use stuff中的所有内容,除了Bar。(显然这个示例里我可以只导入Foo,但实际场景中需要导入的项很多,我不想逐个列出除某一项外的所有内容。)


补充说明(避免他人犯同样错误)

我仍想知道如何实现上述需求,但发现自己最初的示例存在错误,特此贴出实际代码供参考:

pub mod stuff{
    pub struct Foo;
    pub struct Bar;
}

pub mod yet_more_stuff{
    use super::stuff::*;
    pub struct Bar{}
    pub struct Baz{
        pub foo : Foo,
        pub bar : Bar
    }
    impl Baz{
        pub fn new() -> Self{
            Self{
                foo : Foo,
                bar : Bar
            }
        }
    }
}

这段代码无法编译,原因是我在一处将Bar定义为struct Bar;,另一处定义为struct Bar{},导致Baz中的bar字段类型是yet_more_stuff::Bar,但Baz::new()中构造的bar值却是stuff::Bar,属于类型冲突,而非下文提到的优先级问题。


内容的提问来源于stack exchange,提问作者Edward Peters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 12:40:00