Rust - .expect()

May 19, 2025

I have some hash map:

let locals: HashMap<String, i32>;
locals = HashMap::new();

When you look an entry up, you use get(). This returns a value as Option<&i32>. Because it is wrapped with Option<V>, you need to unwrap it before use.

let value1 = locals.get(&key).unwrap();

However, it could return None and .unwrap() will panic in that case.

If you are 100% sure that it won’t fail, you might be better to use .expect(msg) instead.

let value2 = locals.get(&key).expect("key/value should exist");

With .expect(), you can give a custom panic message ("key/value should exit") in a way similar to C’s assert(). The return value value2 is &V (here &i32).