我是生锈的新手。我正在尝试实现一个全局静态数组(可以在多线程中访问它)并将一些结构实例插入其中。通过迭代数组,我可以调用这些实例的功能来执行某些操作。但是我遇到了一个问题,即不能插入带有生命周期注释的结构实例。示例代码和错误信息如下。您能提供一些建议吗?预先感谢!
#[macro_use]
extern crate lazy_static;
use std::sync::{Arc, Mutex};
struct Data {
data: Vec<u8>,
}
trait CallbackFn {
fn write_fn(&self, state: &[u8], data: &mut Data);
fn read_fn(&self, data: &mut Data);
}
pub struct ArrayInst {
idstr: &'static str,
cb_fn: Box<CallbackFn + Send>,
}
impl ArrayInst {
fn process_write(&self, i: &[u8], d: &mut Data) {
self.cb_fn.write_fn(i, d);
}
fn process_read(&self, d: &mut Data) {
self.cb_fn.read_fn(d);
}
}
lazy_static! {
static ref INST_ARRAY: Arc<Mutex<Vec<ArrayInst>>> = Arc::new(Mutex::new(vec![]));
}
pub fn inst_push(inst: ArrayInst) {
INST_ARRAY.lock().unwrap().push(inst);
}
pub fn inst_pop() -> ArrayInst {
INST_ARRAY
.lock()
.unwrap()
.pop()
.expect("Cannot find ArrayInst")
}
struct InstTest<'a> {
name: &'static str,
id: &'a u32,
}
impl<'a> InstTest<'a> {
fn new(id: &'a u32) -> Self {
InstTest {
name: "InstTest",
id: id,
}
}
fn register_inst(self) {
let inst = ArrayInst {
idstr: "Test",
cb_fn: Box::new(self),
};
inst_push(inst);
}
}
impl<'a> CallbackFn for InstTest<'a> {
fn write_fn(&self, val: &[u8], data: &mut Data) {
let mut v: Vec<u8> = val.iter().cloned().collect();
data.data.append(&mut v);
println!("save val is {:?}", val);
}
fn read_fn(&self, data: &mut Data) {
println!("load val is {:?}", data.data);
println!("Current component name is {}", self.name);
}
}
fn main() {
let i: u32 = 10;
let inst = InstTest::new(&i);
let mut data = Data { data: Vec::new() };
inst.register_inst();
let inst = inst_pop();
println!("idstr is {}", inst.idstr);
let a = [1u8, 2, 3];
let i: &[u8] = &a;
inst.process_write(i, &mut data);
inst.process_read(&mut data);
}
错误消息:
Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:62:29
|
62 | cb_fn: Box::new(self),
| ^^^^
|
note: first, the lifetime cannot outlive the lifetime 'a as defined on the impl at 51:6...
--> src/main.rs:51:6
|
51 | impl<'a> InstTest<'a> {
| ^^
= note: ...so that the expression is assignable:
expected InstTest<'_>
found InstTest<'a>
= note: but, the lifetime must be valid for the static lifetime...
= note: ...so that the expression is assignable:
expected std::boxed::Box<(dyn CallbackFn + std::marker::Send + 'static)>
found std::boxed::Box<dyn CallbackFn + std::marker::Send>
error: aborting due to previous error