I have this function that sends an HTTP request parses the response and returns a Result
:
pub fn get_network_info(&self) -> Result<NetworkInfoResult, &'static str> {
let rpc = JsonRpc::new(
String::from("1.0"),
self.settings.id.clone(),
String::from("getnetworkinfo"),
Vec::new(),
);
let url = format!("http://{}:{}", self.settings.url, self.settings.port);
let req = HttpRequest::new_json_rpc(
url,
rpc,
self.settings.user.clone(),
self.settings.pass.clone(),
);
match req.execute() {
Ok(x) => {
println!("{}", x.content);
let parsed: NetworkInfo = serde_json::from_str(&x.content)
.expect("Failed to parse networkinfo Json response");
if parsed.id != self.settings.id {
Err("RPC Request and Response id didn't match!")
} else {
if parsed.error.is_some() {
Err(&parsed.error.unwrap())
} else {
Ok(parsed.result)
}
}
}
Err(e) => Err(e),
}
}
If the error field is set in the JSON response we want to return an error, in particular the error message inside the response. Otherwise, we return the result field of the parsed response.
The problem which this code is that Err(&parsed.error.unwrap())
doesn't compile. The reason for this is that the lifetime of the variable containing the parsed.error.unwrap()
is only within the function, therefore it might not exist anymore in the context of the caller.
My problem is that Err
expects a reference to a string, but whatever reference I try to pass would be to a local or temporary variable. How do I work around this issue?