从 Result<Box<Any>、Box<Error>> 解压到 float32 rust。怎么办?

问题描述 投票:0回答:1
struct ExchangeCurrencyRequestsMock {
  base: String,
  to: String,
  amount: f32,
}
use core::any::Any;
use task::api::Requests;
use std::error;
use serde_json::Value;
use serde_json::Map;

type Result<T> = std::result::Result<T, Box<dyn error::Error>>;

impl Requests for ExchangeCurrencyRequestsMock {
    async fn call(&mut self) -> Result<Box<dyn Any>> {
        let data = r#"
            [
              "USD": {
                "USD": "1.0",
                "PLN": "3.96",
                "AUD": "1.52",
                "EUR": "0.92"
              },
              "PLN": {
                "PLN": "1.0"
                "USD": "0.25",
                "AUD": "0.38",
                "EUR": "0.23"
              }
            ]
        "#;
        let resp: Result<Box<serde_json::Value>> = Ok(serde_json::from_str(&data)?);
        match resp {
            Ok(value)  => {
              let obj: Map<String, Value> = value.as_object().unwrap().clone();
              let ratio: f32 = obj[&self.base.to_ascii_uppercase()][self.to.to_ascii_uppercase()].to_string().parse()?;

              return Ok(Box::new(ratio*self.amount))
            },
            Err(_) => {
              let b: Box<dyn error::Error> = "Request got bad".into();

              return Err(b)
            },
        };
    }
}

#[tokio::test]
async fn call() {
      let mut client = ExchangeCurrencyRequestsMock{
        base: "USD".to_string(),
        to: "AUD".to_string(),
        amount: 100.0,
      };
      let result: std::result::Result<Box<dyn Any>, Box<dyn std::error::Error>> = client.call().await;
      assert_eq!(result, 152.0);

}

如何从 client.call 返回 f32 ?我应该解开结果以获取 Box,然后 * 到 Box,获取 Any 并将其向下转换为 float32 并断言它。我就是这样做的,然后我删除了它,因为它不起作用。

我打开结果以获取 Box,然后 * 到 Box,获取 Any 并将其向下转换为 float32 并断言它,但它不起作用

testing rust mocking rust-tokio serde-json
1个回答
0
投票

查看Any

文档,
downcast
是在
Box<dyn Any>
上实现的,它返回一个
Result<Box<T>, Box<dyn Any>>

所以,我们要做的就是:

*result.unwrap().downcast::<f32>().unwrap()

这会解开原始的

Results
,向下转换为
f32
,然后再次解开(因为
dyn Any
可能不是
f32
类型),然后移出返回的
Box<f32>

但是,由于奇怪的代码架构,这听起来像是一个 XY 问题,也许应该更改

Requests
特征以使其更易于使用?

© www.soinside.com 2019 - 2024. All rights reserved.