Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
737 views
in Technique[技术] by (71.8m points)

rust - How to reference private types from public functions in private modules?

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

This fails with the error

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...