My failing code (Minimal, Reproducible Example):
// my code
fn test() {
let mut list: Vec<Text> = Vec::new();
const ARRAY: [char; 3] = ['a', 'b', 'c'];
for (i, _) in ARRAY.iter().enumerate() {
list.push(Text::new(&ARRAY[i].to_string()));
}
}
// external crate
#[derive(Debug, Clone, Copy, PartialEq)]
struct Text<'a> {
pub text: &'a str,
}
impl<'a> Text<'a> {
pub fn new(text: &'a str) -> Self {
Text {
text
}
}
}
The compiler: "temporary value dropped while borrowed". Red squiggly lines below
ARRAY[i].to_string()
Classic borrow checker problem, I guess?
I tried to change up the types to be &str
s instead of char
s and everything worked fine:
// my code
fn test() {
let mut list: Vec<Text> = Vec::new();
const ARRAY: [&str; 3] = ["a", "b", "c"]; // CHANGE HERE
for (i, _) in ARRAY.iter().enumerate() {
list.push(Text::new(&ARRAY[i])); // CHANGE HERE
}
}
Can't figure out what's so special about char
or the conversion with to_string()
that makes this code fail.