Hi there!
I'm getting stuck trying to work with nested Option<T>. Let's say I have the following struct:
#[derive(Deserialize, Serialize)]
struct MyAppConfig {
port: u16,
api_key: String,
private_key: Option<String>,
file_roots: HashMap<String, PathBuf>,
module_config: SomeSubModuleConfig, // I'll skip defining this one here
}
I read the file with serde in some load_config function or something similar and return a Option<MyAppConfig> from there. Now we get to my problem: how do I access the fields there ergonomically? I referenced TypeScript in my question title because my brain (which is very used to thinking in "the TypeScript way") wants to do something like the following:
const apiKey = config?.apiKey;
if (!apiKey) throw Error(…);
console.log(`Using api key: ${apiKey}`);
const privateKey = config?.privateKey ?? generateNewPrivateKey();
console.log(`Using private key: ${hash(privateKey)}`);
And with Rust I'm trying to translate this to something like (trying to avoid .clone()):
const api_key = config.map(|c| c.apiKey).take().unwrap_or_else(generateNewApiKey);
const private_key = config.map(|c| private_key).flatten().take().unwrap_or_else(generateNewPrivateKey);
But all my attempts at wrangling this into code that'd pass the borrow checking fail.
I don't like the idea of doing a let Some(config) = config with two paths, since then I'm writing the code that calls the generateNewKey functions twice. So, any pointers on how to do this ergonomically?
