"A slice is a kind of reference, so it does not have ownership."
The following code is simplified. It needs to return a slice using a match
. All but one match arm return a string slice. One arm needs to add single quotations around a slice, thus we turn to using format!
that returns String
. The String must then convert to &str
.
The error shows that the resulting slice is referenced by the temporary String in the match arm.
11 | ret
| ^^^ returns a value referencing data owned by the current function
The simplified code as follows. Note we are not using literals but a &str
returned from a third party crate.
fn my_func(input: &str) ->&str {
let ret =
match input {
"a" => "Apha", // in fact, a &str from a crate
_ => format!("'{}'", "Quoted" ).as_str(),
};
ret
}
&str
is desired because that &str
is then pushed using push_str()
.
fn main() {
let mut s = String::new();
s.push_str(my_func("a"));
...
What is your recommendation for copying the str or derefencing the temp string within the match?