如何从私有模块中的公共函数引用私有类型? [英] How to reference private types from public functions in private modules?

查看:87
本文介绍了如何从私有模块中的公共函数引用私有类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件中的相似功能分组.这些函数需要返回非公共类型:

I want to group similar functions in a file. Those functions need to return a type which is not public:

struct MyStruct;

mod my_mod {
    use super::MyStruct;

    // There are other, similar functions that also return `MyStruct`
    pub fn foo() -> MyStruct {
        MyStruct
    }
}

fn main() {
    let _var = my_mod::foo();
}

这失败并显示错误

error[E0446]: private type `MyStruct` in public interface
 --> src/main.rs:7:3
  |
1 |     struct MyStruct;
  |     - `MyStruct` declared as private
...
7 |         pub fn foo() -> MyStruct { MyStruct }
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't leak private type

通常,不允许公共功能在其签名中使用私有类型是有意义的,但是在这种特定情况下,模块的根级别可以使用结构 .

In general, it makes sense not to allow public functions to have private types in their signature, but in this specific case the structure is available at the modules root level.

是否有一种方法可以在不公开发布MyStruct的情况下提供支持?

Is there a way to support this without making MyStruct public?

推荐答案

我觉得此错误是不必要的.仅当my_modpub或在外部作用域中将函数重新导出时才应该是错误.

I have a feeling that this error is unwarranted. It should only be an error if my_mod is pub or if the functions are re-exported in an outer scope.

也就是说,我找到了一种解决方法:将MyStruct移到同级模块中,并创建MyStruct pub,但不创建该模块.

That said, I found a workaround: move MyStruct to a sibling module and make MyStruct pub, but not the module.

use types::MyStruct;

mod types {
    pub struct MyStruct;
}

mod my_mod {
    use super::MyStruct;

    pub fn foo() -> MyStruct {
        MyStruct
    }
}

fn main() {
    let _var = my_mod::foo();
}

这篇关于如何从私有模块中的公共函数引用私有类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆