How do I handle Result value?

Code:

let window: Window = web_sys::window().unwrap();
let x: Result<JsValue, JsValue> = window.inner_width();

How do I obtain the actual innerWidth value?

Two things:

  1. Read the rust book. It's worth reading for understanding the basics of rust.
  2. Consider posting a minimal working example next time so people can better understand what you want to do.

That said, there are multiple options. Result represents the 'result' of an operation that can fail, i.e. what an error would be in other languages. So it is either Ok(value) or Err(error_message). So you can do one of the following (not tested):

let window: Window = web_sys::window().unwrap();
let x: Result<JsValue, JsValue> = window.inner_width();

// Unwrap the value. Will panic if it is the Err variant.
let js_val = x.unwrap();

// Handle both cases explicitly with a match statement.'
let js_val = match x {
    Ok(js_val) => js_val,
    Err(error_message) => {For example return some default value}
};

// Use an if let statement.
if let Ok(js_val) = x {
    {do something with js_val}
} else {
    {do something in error case}
}

// Use one of the methods defined on Result. E.g.
let js_val = x.unwrap_or({some default value});

Note: You cannot execute all of the above solutions at once, since x will be consumed by all of them. So you'd have to uncomment all except one of them.

By the way, on the first line, this is also a Result or an Option being returned by the web_sys::window() method that is being unwrapped with a call to unwrap().

4 Likes

I can't seem to make this work: " no method named unpack found for enum Result in the current scope
method not found in Result<JsValue, JsValue>rustcE0599".

Unwrap works, that's all I need thx.

Ah yeah, my mistake. I'll correct it.

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.