Define variable only if "option"-value is not "none", otherwise call function/struct-method?

Hi all

I'm new to Rust and I'd like to know if what I'm doing is sub-optimal.

Question/problem:
Is there a quick/succinct way to examine the contents of an "option"-variable and then A) if the value is not "None" then use/return it, otherwise B) if the value is "None" then call a function (which in my case would nicely abort my program)?

Here is my current (simplified) code:

let mut my_hashmap:HashMap<String, String> //Create a hashmap

//...HERE I FILL THE HASHMAP WITH KEY-VALUE PAIRS...

//Get from the hashmap the value of the key "the_key_i_am_looking_for"
let myvar = match my_hashmap.get("the_key_i_am_looking_for") {
			Some(s) => s
			,None => {
				my_struct.err("Key \"the_key_i_am_looking_for\" could not be found.");
			}
		};

As you can see I call ".get()" to find a specific key which is supposed to be in my hashmap => the method returns an "option"-variable.

  • If the key is found then the program would be happy, therefore it would assign the key's value to the variable "myvar"...
  • ...but if the key is not found then the program calls the struct's "my_struct" method "err()" which prints to console & writes to the logfile & terminates nicely my program's threads & etc... .

The code above does work, but I feel like that it's a lot of stuff (barely fits on a single line).
Is there a better way to do that?

Cheers :smiley:

    let myvar = my_hashmap
        .get("the_key_i_am_looking_for")
        .unwrap_or_else(|| my_struct.err("Key \"the_key_i_am_looking_for\" could not be found."));

(playground)

1 Like

Damn, I did try some "_or_else"-variant with a closure yesterday evening but that time it did not work, now it works :stuck_out_tongue:
Thanks a lot! :smiley:

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.