如何在impl中使用struct?

时间:2017-12-21 18:23:13

标签: rust

我正在尝试使用Rust的文档中描述的implement a web server using using a thread pool。应用程序的代码位于 src / bin / main.rs 中,库的代码位于 src / lib.rs 中。

尝试使用PoolCreationError会出错:

pub struct ThreadPool;

struct PoolCreationError;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: u32) -> Result<ThreadPool, PoolCreationError> {
        if size > 0 {
            Ok(ThreadPool)
        } else {
            Err(PoolCreationError)
        }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
    }
}
error[E0446]: private type `PoolCreationError` in public interface
  --> src/main.rs:13:5
   |
13 | /     pub fn new(size: u32) -> Result<ThreadPool, PoolCreationError> {
14 | |         if size > 0 {
15 | |             Ok(ThreadPool)
16 | |         } else {
17 | |             Err(PoolCreationError)
18 | |         }
19 | |     }
   | |_____^ can't leak private type

如何应对它并使用结构?

1 个答案:

答案 0 :(得分:2)

pub fn new(…) -> Result<…, PoolCreationError>是指struct PoolCreationError,它是私有的(默认情况下,项目是其模块专用的)。

Rust不允许公共函数公开私有类型。您还需要将类型公开:

pub struct PoolCreationError;

https://doc.rust-lang.org/error-index.html#E0446