Inside a function that returns a &'a str
, I created a String
.
I want to return a &'a str
with the same contents than this String
fn givesString(A: &str) -> String {
String::from("example")
}
pub struct S<'a> {
pub strField: &'a str,
}
impl<'a> S<'a> {
pub fn from_String_A(A: &'a str) -> Result<Self, Box<dyn std::error::Error>> {
let processed_String = givesString(&A);
let processed_str: &'a str = a_processed_String.as_str();
Ok(Self {
strField: processed_str,
})
}
}
which doesn't compile: the borrowed value a_processed_String does not live long enough
, since it's dropped at the end of the function.
I understand the String
will be dropped no matter what.
But now, if I create a &'a str
and pass it into the return value, it compiles with no issue:
fn givesString(A: &str) -> String {
String::from("example")
}
pub struct S<'a> {
pub strField: &'a str,
}
impl<'a> S<'a> {
pub fn from_String_A(A: &'a str) -> Result<Self, Box<dyn std::error::Error>> {
let longlife: &'a str = "hello from the outside of this fn";
Ok(Self {
strField: longlife,
})
}
}
So, is it possible to create a new &'a str
that, instead of borrowing from the String
that will be dropped, simply points to some memory with a lifetime 'a
that holds the same contents as the String
?
There has been countless similar questions where the answer was to simply return a String
instead, but let's assume I cannot touch the code for givesString
or the struct S