I boiled my code down to these lines:
#[derive(Debug)]
struct Config {
values: Vec<String>,
compiled: Option<Vec<String>>,
}
impl Config {
fn comp_values(&mut self) -> &Vec<String> {
if self.compiled.is_none() {
self.compiled = Some(self.values.clone());
}
self.compiled.as_ref().unwrap()
}
fn comp_values_match(&mut self) -> &Vec<String> {
match self.compiled {
Some(_) => self.compiled.as_ref().unwrap(),
None => {
self.compiled = Some(self.values.clone());
self.compiled.as_ref().unwrap()
}
}
}
}
fn main() {
let mut c = Config {
values: vec![String::from("a"), String::from("b")],
compiled: None,
};
println!("config before: {:?}", c);
println!("compiled: {:?}", c.comp_values());
println!("config after: {:?}", c);
}
What I would like to have is something like:
match self.compiled {
Some(v) => v,
None => {
// assemble v and assign it to self.compiled
v
},
}
just like in the closure chapter in the book. Is it possible in the book it only worked, because u32
implements the Copy
trait? If I change the match
line to match self.compiled.as_ref()
the Some(v) => v,
works. In the None
arm I then can't assign like self.compiled = ...
since I have have the variable 'open' (or referenced with self.compiled.as_ref()
) in that block.
Are my assumptions correct? Is the comp_values()
method the most elegant solution in that case?