Organizing this code


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());
} else {

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?


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 {
    } else {

fn create_string() -> String {
fn some_str_ref_op(r: &str) {}
fn some_other_str_ref_op(r: &str) {}


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