Should I use a lifetime parameter?


#1

I have defined a struct like

struct Struct<'a> {
    key: &'a str,
}

However, I feel that the lifetime parameter makes it somewhat complex when I wrap it in another type:

enum Enum<'a> {
   Empty,
   Struct(Struct<'a>),
   List(Vec<Enum<'a>>),
}

Should I remove the lifetime parameter and use 'static instead?

struct Struct {
    key: &'static str,
}

enum Enum {
   Empty,
   Struct(Struct),
   List(Vec<Enum>),
}

I would like to know what are the advantages and disadvantages of using 'a compared to 'static. Any suggestions on these two choices? Thanks!


#2

If you only ever use string-literals and never read anything from a file or the network then you can use &'static str. If you ever borrow a String, then you cannot use &'static str, as the String is not guaranteed to live forever. In that case it might be better to use String instead of str in your structure. Since you are using Vec, you are allocating anyway.


#3

Thanks! If I use String, the struct cannot be copied. I need this

#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
struct Symbol<'a> {
    key: &'a str,
}

#4

The Rust-compiler does this by not using String, but a newtype around u32, which can then be used to extract the actual string from e.g. a HashMap. But that means that you need access to the string database whenever you need information about the actual textual representation.


#5

Vec can’t be Copy either. If your structure holds on to heap memory, it should generally be Clone, not Copy, and the derive should work with just Clone. Most use cases will be fine with just Copy; if yours isn’t, I’d like to know more details so I can give more specific advice.


#6

Yes, you are right. But I only want the Struct to be copied, but not the Enum.