Giving a conditionally created value a longer lifetime?

The following code makes the compiler happy, but I wish using tmp_config weren’t necessary:

impl InlineParser {
    pub fn new(config_opt: Option<&InlineParserConfig>) -> Self {
        let tmp_config: InlineParserConfig;
        let config = match config_opt {
            Some(c) => c,
            None => {
                tmp_config = InlineParserConfig::new();
        // ···
    // ···

Should already be the best solution. You might be able to get away without the type signature in the let tmp_config statement.

1 Like

If InlineParserConfig::new() is a const fn, you can define a const DEFAULT_PARSER_CONFIG_REF: &InlineParserConfig = InlineParserConfig::new(); and then just use config_opt.unwrap_or(DEFAULT_PARSER_CONFIG_REF).

Of course it can only be const fn if none of its fields require allocations.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.