rust - 我可以在 Rust 中创建一个包含字符串和该字符串切片的结构吗?

标签 rust borrow-checker borrowing

我正在尝试创建一个结构,它接受一个输入字符串(并取得它的所有权),进行一些计算,然后返回一个包含该字符串和一些预先计算的字符串切片的结构。
就像是:

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
有没有办法完成我想要做的事情?

最佳答案

你能做到吗costly_search()将开始和结束索引返回到字符串中,并将它们传递给 MyString::new() ?然后你可以每次都创建一个新的切片

fn get_slice(&self) -> &str {
  &self.contents[self.start..self.end]
}

关于rust - 我可以在 Rust 中创建一个包含字符串和该字符串切片的结构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63526813/

相关文章:

rust - 为什么 Rust 从特征到特征的 const 分配不起作用?

rust - 如何限制关联类型接受任何引用生命周期?

rust - 迭代递归结构时无法获取可变引用 : cannot borrow as mutable more than once at a time

rust - 对指针和它指向的结构的生命周期参数使用相同的生命周期

rust - 当返回对范围外值的可变引用的不可变引用时,为什么在范围结束时丢弃可变引用?

string - 用空格替换选项卡

rust - 如何链接采用先前结果并满足严格顺序的函数?

rust - Rust match 语句的赋值

rust - 使用生命周期参数为特征分离可变借位

rust - 从结构字段分配变量时为 "cannot move out borrowed content"