我正在尝试使用r2d2 postgres crate创建连接池,并将其保存在struct DBPool中,以便我可以将此实例传递给dbConn的不同处理程序,但在编译期间会出现不匹配错误。由于PostgresConnectionManager实现了ManageConnection特性,因此无法弄清楚这种不匹配的原因,所以这里缺少什么。
提前致谢。
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}
}
}
编译错误:
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`.
答案 0 :(得分:1)
问题是1与2不匹配:
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
,
例如,这样的签名允许你写:
let d = DBPoll::<SqliteConnectionManager>::new();
所以rustc
报告语法错误,以解决您应该指定的此问题
确切类型:
fn new() -> DBPool<PostgresConnectionManager> {