reference - body 上定义的生命周期 'a 不一定比 body 上定义的匿名生命周期 #1 长

标签 reference rust lifetime

我正在尝试创建一个向数组添加元素的函数 (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 来实现我想要做的事情?

最佳答案

您需要为切片参数指定生命周期:

fn f1<'b, 'a: 'b>(s: &'a str, data: &'b mut [T1<'a>]) {
    data[0] = T1::<'a> { value: s };
}

关于reference - body 上定义的生命周期 'a 不一定比 body 上定义的匿名生命周期 #1 长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42745363/

相关文章:

rust - 删除引用的对象后引用保持有效多长时间?

javascript - 当放置在单独的文件中时,通过 React.js 中的 ref 从父组件调用时,子函数无法访问

utf-8 - 如何在Rust中逐行读取非UTF8文件

c++ - 如何在 C++ 中创建类对象的 vector ?

asynchronous - 如何使用async_std::task::sleep来模拟阻塞操作?

rust - 匿名切片生命周期

google-app-engine - GAE 内存缓存生命周期非常短

rust - 为什么不能在同一结构中存储值和对该值的引用?

c++ - 将好友的引用成员初始化为类私有(private)成员

java - 通过套接字传递对(大)数据区域的引用