簡體   English   中英

在此 scope 中找不到類型“F”

[英]Cannot find type `F` in this scope

這似乎很明顯,但我想從中學到一些東西。 我正在做一些練習,重新實現本書第 20 章的“多線程 http 服務器”。 這並不完全相同(就像我沒有使用Box來保存任務關閉一樣),但這並不重要。

use std::{thread};
use std::sync::{mpsc, Arc, Mutex};

pub struct Executor {
    threads: Vec<thread::JoinHandle<()>>,
    sender: mpsc::Sender<FnOnce() + Send + 'static>,
}

impl Executor {
    pub fn new(thread_num: usize) -> Executor {
        let (tx, rx) = mpsc::channel();
        let rx = Arc::new(Mutex::new(rx));
        let mut threads = Vec::with_capacity(thread_num);

        for i in 0..thread_num {
            let handle = thread::spawn(|| {
                loop {
                    let rx = rx.lock();
                    let f = rx.recv().unwrap();
                    f();
                }
            });
            threads.push(handle);
        }
        Executor { threads, sender: tx }
    }


    pub fn run(&mut self, f: F)
        where
            F: FnOnce() + Send + 'static, {      //*** the compile complains here***
        // let bf = Box::new(f);
        self.sender.send(f);
    }
}

但是,編譯器說:

error[E0412]: cannot find type `F` in this scope
  --> src\lib.rs:31:13
   |
31 |             F: FnOnce() + Send + 'static, {
   |             ^ help: a trait with a similar name exists: `Fn`
   | 
  ::: C:\Users\ynx\.rustup\toolchains\stable-x86_64-pc-windows-gnu\lib/rustlib/src/rust\library\core\src\ops\function.rs:67:1
   |
67 | pub trait Fn<Args>: FnMut<Args> {
   | ------------------------------- similarly named trait `Fn` defined here

我哪里錯了?

您需要使用<F>聲明您的泛型:

pub fn run<F>(&mut self, f: F)
    where
        F: FnOnce() + Send + 'static, { 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM