如何在impl中使用struct?

问题描述 投票:-3回答:1

我正在尝试按照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

如何应对它并使用结构?

rust
1个回答
2
投票

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

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

pub struct PoolCreationError;

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

© www.soinside.com 2019 - 2024. All rights reserved.