【问题标题】:Can I create a struct in Rust containing a String and a slice of that String?我可以在 Rust 中创建一个包含字符串和该字符串切片的结构吗?
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我会试试的。每次调用者想要访问它时创建这样的切片是否“便宜”?
    • 一个切片基本上只是两个“usize”大小的变量,所以它很便宜。
    • freenode irc 网络上漂亮的##rust 频道上的一位朋友透露,您可以使用std::ops::Range 而不是两个单独的开始和结束字段。然后你可以改为&amp;self.contents[self.range]
    猜你喜欢
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多