Sarp Başaraner
Sarp Başaraner

Reputation: 516

Is it possible to initialize immutable variables with match in Rust?

I have this piece of code where I try to convert command line arguments to integers. The problem is, the variables width and height should really be immutable, as I don't plan to change them. Is there any way I can use match like let width = {match....} and initialize them in one step as immutable variables rather than giving them a default value and mutating them? I believe this would be safer and more efficient.

let args: Vec<String> = env::args().collect();
let width_arg = &args[1];
let height_arg = &args[2];

let mut width = 0;
let mut height = 0;

match width_arg.parse::<i32>() {
    Ok(w) => width = w,
    Err(_) => ask_for_number(),
}

match height_arg.parse::<i32>() {
    Ok(h) => height = h,
    Err(_) => ask_for_number(),
}

Upvotes: 1

Views: 708

Answers (2)

grovesNL
grovesNL

Reputation: 6075

Sure, match is an expression, so you should be able to rewrite it as follows:

let args: Vec<String> = env::args().collect();
let width_arg = &args[1];
let height_arg = &args[2];

let width = match width_arg.parse::<i32>() {
    Ok(w) => w,
    Err(_) => ask_for_number(),
};

let height = match height_arg.parse::<i32>() {
    Ok(h) => h,
    Err(_) => ask_for_number(),
};

Upvotes: 8

Liam Borella
Liam Borella

Reputation: 31

Yes, just initialise the variable like so: let a = match b { /* your code here*/ };

Upvotes: 2

Related Questions