I guess this is a quite basic Rust question, but I have this piece of code
struct Stock<'a> {
name: &'a str,
value: u8,
}
impl<'a> Stock<'a> {
fn read(file: &mut File) -> Stock<'a> {
let mut value = vec![0; 1];
file.read(&mut value);
let name_size = read_u32(file);
let mut name = vec![0; name_size as usize];
file.read(&mut name);
return Stock {
name: str::from_utf8(&name).unwrap(),
value: value[0],
};
}
}
and of course, it doesn't work, because I am referencing a local value name. To my limited knowledge, this is because outside the scope of read
, name
doesn't exist. However wouldn't from_utf8
create a new variable that is not scoped to read
?
Also, I've read a bit about other people with this issue, and the suggestion is always to switch to the owned String
. But why can't I do something such as name: str::from_utf8(&name).unwrap().to_owned()
?