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