You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中deadpool_postgres获取Client返回Future而非实例问题求解

错误原因
  • async 函数调用后默认返回 Future 类型对象,必须添加 .await 执行后才能拿到函数声明的返回值,你调用get_client时未加.await,因此得到的是Future对象而非预期的Client实例。
  • get_client方法的返回值声明与实际返回逻辑不匹配:方法内部返回Some(client)和None属于Option<Client>类型,但签名写的返回值是Client,属于类型错误。
  • 存在未导入的依赖项:Pool、ManagerConfig、RecyclingMethod均需要从deadpool_postgres包中显式导入。
  • Rust原生不支持异步main函数,需要配套异步运行时的入口宏才能正常执行异步逻辑。
修复后代码
// 补全所有需要导入的依赖项
use deadpool_postgres::{Config, Pool, Client, ManagerConfig, RecyclingMethod};
use tokio_postgres::NoTls;

pub struct Postgres {
    pool: Pool
}

impl Postgres {
    pub fn new() -> Postgres {
        let mut cfg = Config::new();
        cfg.dbname = Some("deadpool".to_string());
        cfg.manager = Some(ManagerConfig { recycling_method: RecyclingMethod::Fast });
        let pool = cfg.create_pool(NoTls).unwrap();
        Postgres { pool }
    }
    
    // 修正返回值类型为Option<Client>,匹配实际返回逻辑
    pub async fn get_client(&self) -> Option<Client> {
        self.pool.get().await.ok()
    }
}

#[tokio::main] // 添加tokio异步运行时的入口宏,支持异步main
async fn main() {
    let pg = Postgres::new();
    // 添加.await执行Future拿到Option<Client>,此处用unwrap简单解包,生产环境建议用match处理None异常场景
    let client = pg.get_client().await.unwrap();
    let stmt = client.prepare_cached("select 1").await.unwrap();
}

内容的提问来源于stack exchange,提问作者ferd tomale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:12:01