How to avoid (mandatory) lifetime specification in struct?

struct StringExample<'a>
    name : String,
    name_part : &'a str,
impl<'a> StringExample<'a>
    fn new() -> StringExample<'a>
        let s : String = "hallo".to_string();
        let n : &str = s.as_str();
        StringExample{name : s,name_part : n }

I have an owned String within a Struct (name), a slice (name_part) within that struct should contain a reference into that string. It should be ok because the lifetime of the slice is that of the String.
I want the compiler to understand the reference “name_part” is a reference to the contained String “name” .
QUESTION 1: Is this fact somehow presentable to the compiler ?

QUESTION 2: Is it possible to encapsulate a struct with lifetime parameter so that it can be used without specifying the lifetime on the complete call hierachy ?


No, rust’s type system can not express this situation in safe code. It falls under the common theme of one struct member wanting to have a reference to another part of the same struct.


You could instead store the name_part as offset and length usizes, and get the &str slice on demand.


owning_ref’s StringRef also implements this particular thing – a String paired with a &str pointing into it.