A lifetime problem

struct S<'a>

{

    s:&'a str,

    d:String,

}

impl <'a> S<'a>

{

    fn new<'b>()->S<'b>

    {

        S

        {

            s:"",

            d:"".to_string(),

        }

    }

    fn f1(&mut self,s:&'a String)

    {

        let v:Vec<_>=s.split('=').collect();

        if v.len()>0

        {

            self.s=v[0];

        }

    }

    fn f2(& mut self,input:&[u8])

    {

        let v=Vec::from(input);

        let s=String::from_utf8(v);

        if s.is_ok()

        {

            let s=s.unwrap();

            self.d=s;

            self.f1(&self.d);

        }

    }

}

fn main() {}

how can i solve this problem?

Please format the code according to this topic - it's hard to understand right now.

2 Likes

The code is still hard to read because there are blank lines in between every line of code. rustfmt will clean this up for you.

In f2 you are trying to make the struct self-referential, that is, to make self.s refer to (part of) self.d. This is occasionally useful but very tricky to do in a way that is provably correct, so the usual advice is to avoid self-referential data structures entirely (for example, just use String).

In many other languages this would work implicitly, either by copying strings or by garbage collection. In Rust you have to be a bit more explicit about these things. This is by design.

If you are struggling to find a way to avoid self-reference, someone might be able to suggest an alternative design, if you explain what it is you're trying to write.

I would guess this person is on windows and the double newlines are actually a carriage return followed by a newline, but non-windows systems interpret it as two newlines.