Converting a String to an &str Rust without resulting in borrowing problem

Viewed 87

Is there someway to convert a String (function parameter) into &str (used in return value) while avoiding borrowing problems or referencing a temporary value.

Here is an example use case:

PS: I am constrained by existing functions to these types and cannot just change the type of the function's parameter nor its &str consuming return value. Also the following example uses clap::Arg::new to emphasize this aspect.

// f is any iterator over String values, for example sake I am using Vec<String> with literal value which does not represent the real case.
let f: Vec<String> = vec!["A".into(),"B".into(),"C".into()].into_iter();

let arg: clap::Arg = f.map(|s: String|{
    clap::Arg::new(s.as_str())
});
1 Answers

Is there someway to convert a String (function parameter) into &str (used in return value) while avoiding borrowing problems or referencing a temporary value.

No but yes, but, really, no.

"No": if your parameter is a String, then the function owns the String, meaning once the function exits the String will be reclaimed, and so any referenced to that would be invalid as it would be dangling.

"but yes": you can convert the String into a Box<str>, which you can then leak. This returns a &'static str, which will live forever

"but, really, no": while leaking memory is safe as far as Rust is concerned, it's still leaking memory. This might be fine in some contexts (e.g. short-running processes where explicitly freeing is a waste of resources, or some forms of ad-hoc interning), but in general it's really bad practice.

Related