首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回泛型结构时类型不匹配

返回泛型结构时类型不匹配
EN

Stack Overflow用户
提问于 2017-07-22 09:22:04
回答 1查看 203关注 0票数 1

我正在尝试创建连接池,使用r2d2 postgres crate,并将其保存在结构DBPool中,以便我可以将此实例传递给dbConn的不同处理程序,但在编译过程中出现不匹配错误。由于PostgresConnectionManager实现了ManageConnection特征,因此无法找出这种不匹配的原因,所以这里缺少什么。

提前谢谢。

代码语言:javascript
复制
extern crate r2d2;
extern crate r2d2_postgres;

 use std::thread;
 use r2d2:: {Pool, ManageConnection};
 use r2d2_postgres::{TlsMode, PostgresConnectionManager};

fn main() {

    let pool = DBPool::<PostgresConnectionManager>::new();
    println!("{:?}", pool.pool);
}

struct DBPool <M: ManageConnection>{
    pool: Pool<M>
}

impl<M: ManageConnection> DBPool<M> {
    fn new()-> DBPool<M>  {
        let config = r2d2::Config::default();
        let manager = PostgresConnectionManager::new("postgresql://root@localhost:26257/db?sslmode=disable", TlsMode::None).unwrap();
        let p =  r2d2::Pool::new(config, manager).unwrap() ;

        println!("Pool p: {:?}", p);
        DBPool { pool: p}
    }
}

编译错误:

代码语言:javascript
复制
 dbcon git:(master) ✗ cargo run
   Compiling dbcon v0.1.0 (file:///Users/arvindbir/projects/rust/dbcon)
error[E0308]: mismatched types
  --> src/main.rs:42:9
   |
42 |         DBPool { pool: p}
   |         ^^^^^^^^^^^^^^^^^ expected type parameter, found struct `r2d2_postgres::PostgresConnectionManager`
   |
   = note: expected type `DBPool<M>`
              found type `DBPool<r2d2_postgres::PostgresConnectionManager>`

error: aborting due to previous error

error: Could not compile `dbcon`.
EN

回答 1

Stack Overflow用户

发布于 2017-07-22 12:42:31

问题是1与2不匹配:

代码语言:javascript
复制
fn new()-> DBPool<M>/*1*/  {
    let manager = PostgresConnectionManager::new
    let p =  r2d2::Pool::new(config, manager).unwrap() ;
    DBPool { pool: p}/*2*/
}

1中,你告诉我返回任何DBPool<M>,其中M任何实现了ManageConnection的类型,但是在2中,你告诉我改变了主意,我返回特定的M = PostgresConnectionManager,例如,这样的签名允许你写:

代码语言:javascript
复制
let d = DBPoll::<SqliteConnectionManager>::new();

因此rustc报告语法错误,要解决此问题,应指定确切类型:

代码语言:javascript
复制
fn new() -> DBPool<PostgresConnectionManager> {
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45249716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档