我正在尝试创建一个向数组添加元素的函数(f1
)。
这是我的Rust代码:
use std::mem;
struct T1<'a> {
value: &'a str,
}
fn main() {
let mut data: [T1; 1] = unsafe { mem::uninitialized() };
f1("Hello", &mut data[..]);
}
fn f1<'b, 'a: 'b>(s: &'a str, data: &'b mut[T1]) {
data[0] = T1::<'a> { value: s };
}
我收到此错误消息:
error[E0308]: mismatched types
--> <anon>:13:15
|
13 | data[0] = T1::<'a> { value: s };
| ^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
|
= note: expected type `T1<'_>`
= note: found type `T1<'a>`
note: the lifetime 'a as defined on the body at 12:49...
--> <anon>:12:50
|
12 | fn f1<'b, 'a: 'b>(s: &'a str, data: &'b mut[T1]) {
| __________________________________________________^ starting here...
13 | | data[0] = T1::<'a> { value: s };
14 | | }
| |_^ ...ending here
note: ...does not necessarily outlive the anonymous lifetime #1 defined on the body at 12:49
--> <anon>:12:50
|
12 | fn f1<'b, 'a: 'b>(s: &'a str, data: &'b mut[T1]) {
| __________________________________________________^ starting here...
13 | | data[0] = T1::<'a> { value: s };
14 | | }
| |_^ ...ending here
help: consider using an explicit lifetime parameter as shown: fn f1<'b, 'a:'b>(s: &'a str, data: &'b mut [T1<'a>])
--> <anon>:12:1
|
12 | fn f1<'b, 'a: 'b>(s: &'a str, data: &'b mut[T1]) {
| _^ starting here...
13 | | data[0] = T1::<'a> { value: s };
14 | | }
| |_^ ...ending here
有没有办法写f1
做我想做的事情?
答案 0 :(得分:1)
您需要为切片参数指定生命周期:
fn f1<'b, 'a: 'b>(s: &'a str, data: &'b mut [T1<'a>]) {
data[0] = T1::<'a> { value: s };
}