【发布时间】:2020-02-08 08:33:24
【问题描述】:
背景
我正在写一个库,一些相关代码如下所示:
pub struct MyStruct1;
pub struct MyStruct2;
pub enum MyEnum {
Variant1(MyStruct1),
Variant2(MyStruct2)
}
// out of this crate
fn foo(my_enum: Rc<RefCell<MyEnum>>) {
match &*my_enum.borrow() {
Variant1(my_struct1) => { /* do something */ },
Variant2(my_struct2) => { /* do something */ }
}
}
目标
MyEnum 始终使用包裹在Rc<RefCell<MyEnum>> 中。所以我想将它隐藏在is-it-possible-to-implement-methods-on-type-aliases 中描述的新类型结构中:
//make this only public to crate
pub(crate) enum MyEnum;
pub struct ExposedMyEnum(pub(crate) Rc<RefCell<MyEnum>>);
而且我不希望其他使用我的 crate 的人知道Rc<RefCell<>> 的存在。
问题
如果我使用ExposedMyEnum 来隐藏烦人的Rc<RefCell<MyEnum>>,我就不能像foo 那样做模式匹配。
不优雅的解决方案
将原代码改为
struct MyStruct1;
struct MyStruct2;
pub struct ExposedMyStruct1(pub(crate) Rc<RefCell<MyStruct1>>);
pub struct ExposedMyStruct2(pub(crate) Rc<RefCell<MyStruct2>>);
pub enum MyEnum {
Variant1(ExposedMyStruct1),
Variant2(ExposedMyStruct1)
}
// out of this crate
fn foo(my_enum: &MyEnum) {
match &my_enum {
Variant1(my_struct1) => { /* do something */ },
Variant2(my_struct2) => { /* do something */ }
}
}
我需要为每个变体创建新类型结构,这并不优雅。
【问题讨论】:
标签: rust