Copy a &str from another &str with a specific lifetime

Is it possible to copy a &str from another &str with a specific lifetime? For example:

// I would like to create a copy of 's' with the same lifetime that '_t'
fn copy<'a>(_t: &'a str, s: &str) -> &'a str {
    s.clone::<'a>()
}

The previous code produces the following error:

error[E0621]: explicit lifetime required in the type of `s`
help: add explicit lifetime `'a` to the type of `s`: `&'a str`

Trying the suggestion from the error worked for me :slight_smile:. But I may have missed something.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7dc3dbbcde721b242801831f87d5ff33

Yes, but I would like to create a new &str with the same lifetime that '_t' without changing the lifetime of 's'. Although I think that's not possible and this question makes no sense :slight_smile:

Ah, I see. I’m not sure that you can “change” or “assign” a lifetime in the manner you’re trying. Lifetimes are more descriptive than something you control. And when you declare them explicitly, it’s more to inform the compiler of lifetime bounds it may not be able to deduce, rather than to “give” objects a lifetime. If my understanding is incorrect, please feel free to correct.

I’m not as knowledgeable about unsafe rust, but you may be able to manipulate lifetimes in some (not recommended) way there, if really needed.

Can you explain more about what issue you’re trying to solve with your code?

The data needs to be stored in some sort of container that lives long enough. One option would be to have t be mutable and write to it, although it requires t to have enough space or that you have access to the underlying String so you can extend it if it's too short.

Keep in mind that lifetimes don't do anything, and they can't make something live long enough. They only describe what the program is already doing, so that the compiler can check if that's sensible. For example, the alternative mrustc compiler doesn't understand lifetimes, and ignores them completely, and can still run Rust code properly.

&str is not a string in itself, but a view of some other String (or a similar owned type) that lives elsewhere and already has its own lifetime dictated by the code that created it and destroys it. So you can't remotely make something else, somewhere else, live longer.

You probably shouldn't be using &str for this, and use String as the return type.

3 Likes