rust E0597:借入的价值不足以应付生活

问题描述 投票:0回答:1

我正在尝试将算法从javascript重写为rust。在以下代码中,在第17行处出现借入的值寿命不长错误。

[dependencies]
scraper = "0.11.0"
use std::fs;

fn get_html(fname: &str) -> String {
    fs::read_to_string(fname).expect("Something went wrong reading the file")
}

pub mod diff_html {
    use scraper::{element_ref::ElementRef, Html};

    pub struct DiffNode<'a> {
        node_ref: ElementRef<'a>,
    }

    impl<'a> DiffNode<'a> {
        fn from_html(html: &str) -> Self {
            let doc = Self::get_doc(&html);
            let root_element = doc.root_element().to_owned();
            let diffn = Self {
                node_ref: root_element,
            };
            diffn
        }

        fn get_doc(html: &str) -> Html {
            Html::parse_document(html).to_owned()
        }
    }

    pub fn diff<'a>(html1: &str, _html2: &str) -> DiffNode<'a> {
        let diff1 = DiffNode::from_html(&html1);
        diff1
    }
}

fn main() {
    //read strins
    let filename1: &str = "test/test1.html";
    let filename2: &str = "test/test2.html";

    let html1: &str = &get_html(filename1);
    let html2: &str = &get_html(filename2);

    let diff1 = diff_html::diff(html1, html2);

    //write html
    //fs::write("test_outs/testx.html", html1).expect("unable to write file");
    //written output file.
}
warning: unused variable: `diff1`
  --> src\main.rs:43:9
   |
43 |     let diff1 = diff_html::diff(html1, html2);
   |         ^^^^^ help: if this is intentional, prefix it with an underscore: `_diff1`
   |
   = note: `#[warn(unused_variables)]` on by default

error[E0597]: `doc` does not live long enough
  --> src\main.rs:17:32
   |
14 |     impl<'a> DiffNode<'a> {
   |          -- lifetime `'a` defined here
...
17 |             let root_element = doc.root_element().to_owned();
   |                                ^^^--------------------------
   |                                |
   |                                borrowed value does not live long enough
   |                                assignment requires that `doc` is borrowed for `'a`
...
22 |         }
   |         - `doc` dropped here while still borrowed

如果可能,我需要详细的解释/解决方案。

我正在尝试将算法从javascript重写为rust。在以下代码中,我在第17行获得借入的值的寿命不够长错误。[dependencies] scraper =“ 0.11.0”使用std:...

rust reference lifetime ownership
1个回答
0
投票

root_element实际上是ElementRef,它引用了doc内部的对象,而不是实际拥有的对象。这里的对象doc是在from_html函数中创建的,因此归该函数所有。由于未返回doc,因此会在from_html功能块的末尾将其从内存中删除/删除。

© www.soinside.com 2019 - 2024. All rights reserved.