For improved readability, I recommend using rustfmt
on your code before asking a question, and making sure you aren’t messing up your braces (“{
” and “}
”) or other simple errors.
So your code example looks like this
use std::collections::HashMap;
pub struct Smth {
//...
pub your_languages: Option<Vec<String>>,
}
impl Smth {
fn new_lang_vec(&self, cap: Option<usize>) -> Option<Vec<String>> {
const DEFAULT_VEC_CAP: u8 = 12;
if let Some(i) = cap {
Some(Vec::with_capacity(i as usize))
} else {
Some(Vec::with_capacity(DEFAULT_VEC_CAP as usize)) //or Vec::new()
}
}
fn say_smth(&self, available_languages: HashMap<String, String>) {
//1.
let your_ls: &Vec<String> = self
.your_languages
.as_ref() // either it will be moving value and error
.unwrap_or_else(|| {
self.your_languages = self.new_lang_vec(None);
&self.your_languages.unwrap()
}); //.unwrap_or_else(|| Box::new(self.new_lang_vec(Some(None))))
//.... Other stuff...
}
}
So in case you only ever want to replace an uninitialized (i.e. “None”-valued) field with an initialized one, you could use consider using something like OnceCell
.
E.g.
use std::collections::HashMap;
use once_cell::unsync::OnceCell;
pub struct Smth {
//...
pub your_languages: OnceCell<Vec<String>>,
}
impl Smth {
fn new_lang_vec(&self, cap: Option<usize>) -> Vec<String> {
const DEFAULT_VEC_CAP: u8 = 12;
if let Some(i) = cap {
Vec::with_capacity(i as usize)
} else {
Vec::with_capacity(DEFAULT_VEC_CAP as usize) //or Vec::new()
}
}
fn say_smth(&self, available_languages: HashMap<String, String>) {
//1.
let your_ls: &Vec<String> = self.your_languages.get_or_init(|| self.new_lang_vec(None));
//.... Other stuff...
}
}
You can also simplify new_lang_vec
; it doesn’t access/need self
and it could use Option::unwrap_or
use std::collections::HashMap;
use once_cell::unsync::OnceCell;
pub struct Smth {
//...
pub your_languages: OnceCell<Vec<String>>,
}
impl Smth {
fn new_lang_vec(cap: Option<usize>) -> Vec<String> {
const DEFAULT_VEC_CAP: usize = 12;
Vec::with_capacity(cap.unwrap_or(DEFAULT_VEC_CAP))
}
fn say_smth(&self, available_languages: HashMap<String, String>) {
//1.
let your_ls: &Vec<String> = self.your_languages.get_or_init(|| Self::new_lang_vec(None));
//.... Other stuff...
}
}