繁体   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