#unwrap multiple options

1 messages · Page 1 of 1 (latest)

swift notch
#

I'm looking for a more elegant way to unwrap multiple option. and here is the my codes in question:

let acc_id = json_val.get("product_id").unwrap().as_i64().unwrap() as i32; 
let user_agent = json_val.get("user_agent").unwrap().to_string();

To provide more context:

  • both variables are required within a function and should fail if either fails to unwrap
  • json_val is of type JsonValue which is a type from the serde_json lib, pretty much like a hashmap data structure in this case
lilac sand
#

Avoid serde_json::Value 99% of the time

#
#[derive(Deserialize)]
struct Response {
    product_id: i32,
    user_agent: String,
}
swift notch
lilac sand
#

I think the easiëst thing to do would be to make the function return an Option and then use the ? operator