2

Can I conditionally provide an initialization for a vector or no initialization at all?

fn main() {
    let b = true;
    let a = vec![
        if b {"b"} //error[E0317]: `if` may be missing an `else` clause
    ];
    println!("{:?}", a);
}

2 Answers 2

2

The vec! macro doesn't support this, but you can use normal functions on Vec:

fn main() {
    let b = true;
    let mut a = Vec::new();
    if b {
        a.push("b");
    }
    println!("{:?}", a);
}

playground

Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively, just have to different vecs: if b { vec!["b"] } else { vec![] }
If you want to protect immutability in a better way @Masklinn's alternative solution can be much more accurate.
1

You can do this:

let my_vec = if condition {
   vec!["b"]
}
else{
   vec![]
};

Another option is late initialization:

let my_vec: Vec<&str>;

if condition{
   my_vec = vec![];
}
else{
   my_vec = vec!["b"];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.