Organizing this code


#1

Rust novice here. I have this piece of code:

let x = data.some_str_ref();
let mut w = None;
let y = if some_cond() {
    w = Some(create_and_return_some_string());
    w.as_ref().unwrap()
} else {
    x
}
some_str_ref_op(y);
another_str_ref_op(y);
yet_another_str_ref_op(y);

Note that I am using w as essentially a placeholder to keep the new string around if its reference is used. This gives me a warning that the w = None assignment is unused. Is there a better way to organize or rewrite this code to do the same thing and avoid this warning?


#2

You can change let mut w = None; to simply let w; and continue assigning it inside the if arm. The compiler is smart enough to understand that the assignment occurs only once, or none at all, and you don’t need to give it a dummy None initial value.

Another approach, just for kicks and giggles, using Cow:

use std::borrow::Cow;

fn main() {
    let x = "static string";
    let s = if true {
        Cow::from(create_string())
    } else {
        Cow::from(x)
    };
    some_str_ref_op(&s);
    some_other_str_ref_op(&s);
}

fn create_string() -> String {
    "abc".to_string()
}
fn some_str_ref_op(r: &str) {}
fn some_other_str_ref_op(r: &str) {}

#3

Thanks, the let w; syntax was new to me. The Cow approach is also quite enlightening.