【发布时间】:2020-08-21 16:39:27
【问题描述】:
我正在尝试创建一个结构,它接受一个输入字符串(并取得它的所有权),进行一些计算,然后返回一个包含该字符串和一些预先计算的字符串切片的结构。
类似:
pub async fn read_file<'a>(path: &Path) -> Result<MyString<'a>> {
let contents = tokio::fs::read_to_string(path).await?;
let slice = costly_search(&contents);
Ok(MyString::new(contents, slice))
}
pub struct MyString<'a>
{
slice: &'a str,
string: String,
}
impl<'a> MyString<'a> {
pub fn new(string: String, slice: &'a str) -> MyString<'a> {
MyString { string, slice }
}
pub fn get_slice(&self) -> &str {
self.slice
}
}
文件contents 可能很大,所以我不想复制它。函数costly_search 可能需要一些时间来计算,但总是返回其输入的一部分;该切片也很大,因此我不想将该切片复制到新字符串中。这也被简化了;我将在结构中包含多个输入字符串切片,消费者可以传递整个内容并根据需要使用预先计算的切片。
当我尝试编译时,我得到:
`contents` does not live long enough
borrowed value does not live long enough
utils.rs(43, 31): borrowed value does not live long enough
utils.rs(45, 1): `contents` dropped here while still borrowed
有没有办法完成我想做的事情?
【问题讨论】:
标签: rust borrow-checker borrowing