Reputation: 81
I'm trying to create a function (f1
) that adds an element to an array.
Here is my Rust code:
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 };
}
I get this error message:
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
Is there a way to write f1
that does what I'm trying to do?
Upvotes: 3
Views: 3150
Reputation: 33657
You need to specify lifetime to the slice parameter:
fn f1<'b, 'a: 'b>(s: &'a str, data: &'b mut [T1<'a>]) {
data[0] = T1::<'a> { value: s };
}
Upvotes: 1