如何处理方法指针的隐式生存期?

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

在以下代码中,方法Worker::work被传递给函数run_worker_method,但似乎与其中定义了impl<'a>Worker::work块的生命周期参数冲突。但是,可以在冗余寻找功能Worker::work中包装call_worker_work。如何适当/更简洁地处理impl<'a>块的生命周期参数?

pub struct Worker<'a> {
    config: &'a i32,
}

impl<'a> Worker<'a> {
    pub fn work(&mut self) { 
        /* ... */
    }
}

pub fn run_worker_method<F>(f: F)
where
    F: Fn(&mut Worker),
{
    // the following has no impact; given for illustration
    let config = 0;
    let mut worker = Worker { config: &config };
    f(&mut worker);
}

pub fn use_run_worker_method() {
    // How to make this line compile?
    run_worker_method(Worker::work);

    // This does compile.
    run_worker_method(call_worker_work);
    run_worker_method(|worker| worker.work());
}

pub fn call_worker_work(worker: &mut Worker) {
    worker.work()
}

编译器消息:

error[E0631]: type mismatch in function arguments
  --> src/lib.rs:23:23
   |
6  |     pub fn work(&mut self) { 
   |     ---------------------- found signature of `for<'r> fn(&'r mut Worker<'_>) -> _`
...
11 | pub fn run_worker_method<F>(f: F)
   |        -----------------
12 | where
13 |     F: Fn(&mut Worker),
   |        --------------- required by this bound in `run_worker_method`
...
23 |     run_worker_method(Worker::work);
   |                       ^^^^^^^^^^^^ expected signature of `for<'r, 's> fn(&'r mut Worker<'s>) -> _`

error[E0271]: type mismatch resolving `for<'r, 's> <for<'t0> fn(&'t0 mut Worker<'_>) {Worker::<'_>::work} as std::ops::FnOnce<(&'r mut Worker<'s>,)>>::Output == ()`
  --> src/lib.rs:23:5
   |
11 | pub fn run_worker_method<F>(f: F)
   |        -----------------
12 | where
13 |     F: Fn(&mut Worker),
   |        --------------- required by this bound in `run_worker_method`
...
23 |     run_worker_method(Worker::work);
   |     ^^^^^^^^^^^^^^^^^ expected bound lifetime parameter, found concrete lifetime
rust lifetime
1个回答
-1
投票

首先,这:

pub fn run_worker_method<F>(f: F) where F: Fn(&mut Worker) {
  // the following has no impact; given for illustration
  let config = 0;
  let mut worker = Worker { config: &config };
  f(&mut worker);
}

无效,因为您需要传递引用了比run_worker_method长的配置的工作程序。需要更改run_worker_method,以使用对寿命为'a的Worker的引用的功能。

因此,为工作人员的run_worker_method增加了生命周期,并从外部工作中传入了工作人员。

pub struct Worker<'a> {
  config: &'a i32,
}

impl<'a> Worker<'a> {
  pub fn work(&mut self) { /* ... */ }
}

// your config needs to come from outside run_worker_method
pub fn run_worker_method<'a, F>(f: F, worker: &'a mut Worker<'a>) where F: Fn(&mut Worker<'a>) {
  f(worker);
}

pub fn use_run_worker_method() {
  let config = 0;
  let mut worker = Worker { config: &config };
  run_worker_method(Worker::work, &mut worker);
}

fn main() {

}

让我知道我是否误解了这个问题。

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