我正在尝试创建一个函数(f1
),该函数将元素添加到数组中。
这是我的防锈代码:
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
的方法可以做到我想做的? 最佳答案
您需要指定slice参数的生存期:
fn f1<'b, 'a: 'b>(s: &'a str, data: &'b mut [T1<'a>]) {
data[0] = T1::<'a> { value: s };
}