为何无法访问字段?类型`impl Future<...>`无`main`字段报错[E0609]
解决Rust异步函数调用后无法直接访问结构体字段的问题
错误原因
你碰到的E0609错误,核心问题是异步函数调用后返回的是Future类型,不是你期望的WeatherData结构体。get_weather()调用后返回的是impl Future<Output = Result<WeatherData, reqwest::Error>>,这个Future代表一个尚未完成的异步任务,必须等它执行完成才能拿到实际结果,自然没法直接访问main字段。
修正方案
要解决这个问题,需要两步:
- 在异步上下文中用
.await等待Future完成,拿到Result<WeatherData, reqwest::Error>; - 处理
Result类型,提取出内部的WeatherData结构体(同时处理可能的错误)。
另外注意:原代码里Main的temp定义为Vec<f32>是错误的,OpenWeatherMap的weather接口返回的main.temp是单个浮点数,需要改成f32。
修正后的完整代码
use serde::Deserialize; // 需在Cargo.toml中添加serde和reqwest依赖 #[derive(Debug, Deserialize, Clone)] struct WeatherData { main: Main, } #[derive(Debug, Deserialize, Clone)] struct Main { temp: f32, // 修正为单个浮点数,匹配接口返回格式 } async fn get_weather() -> Result<WeatherData, reqwest::Error> { reqwest::get("https://api.openweathermap.org/data/2.5/weather?q=neftekamsk&units=metric&cnt=8&appid=apikeyhere") .await? .json::<WeatherData>() .await } // 将test改为异步函数 async fn test() -> Result<(), reqwest::Error> { // 等待异步任务完成,提取结果 let weather_data = get_weather().await?; // 现在可正常访问结构体字段 println!("涅夫捷卡姆斯克当前温度: {}°C", weather_data.main.temp); Ok(()) } // 使用tokio runtime运行异步主函数(需在Cargo.toml添加tokio依赖) #[tokio::main] async fn main() -> Result<(), reqwest::Error> { test().await }
额外说明
- 异步函数必须在异步上下文中执行,所以
test要改成async fn,而Rust默认的main是同步函数,需要用runtime(比如tokio)包装成异步主函数; ?操作符用来快速处理Result:如果是Ok就提取内部值,如果是Err就直接返回错误,你也可以用match或if let手动处理错误分支。
内容的提问来源于stack exchange,提问作者Marie
相关产品推荐
相关产品推荐

