我試圖做出Entity
接口,用於動態映射數據庫結果變成鐵鏽結構:使用特質的接口,用於數據庫實體
pub trait Entity {
fn map(&self, Result<QueryResult>) -> Self;
}
pub struct DbQuery<T> {
pub sql: String,
pub params: Vec<Value>,
pub limit: i32,
pub paged: Option<Pagination>,
pub entity: T,
}
pub struct Settings {
pub name: String,
pub value: Option<String>,
}
impl Entity for Settings {
fn map(&self, result: Result<QueryResult>) -> Settings {
// ...
Settings {
name: "hello".to_string(),
value: None,
}
}
}
impl DbMapper {
// ...
pub fn find<T>(&self, query: DbQuery<T>) -> Option<Vec<T>> {
println!("query find SQL: {}", query.sql);
let mut stmt = &self.pool.prepare(query.sql).unwrap();
let ret = Vec::new();
for row in stmt.execute(query.params).unwrap() {
ret.push(query.entity.map(row.unwrap()));
}
Some(ret)
}
}
但我得到一個錯誤:
error: no method named
map
found for typeT
in the current scope
ret.push(query.entity.map(row.unwrap())); |
note: the methodmap
exists but the following trait bounds were not satisfied:T : std::iter::Iterator
= help: items from traits can only be used if the trait is implemented and in scope; the following traits define an itemmap
, perhaps you need to implement one of them: = help: candidate #1:models::holders::database::Entity
= help: candidate #2:std::iter::Iterator
你的例子並不完全站在它自己的最小例子,但我認爲答案是你沒有限制'T'來在'DbQuery'和/或'DbMapper ::中實現'Entity' find'。 –
對不起,我使用最小的代碼來解釋它。 不幸的是,我已經嘗試過與實體,而不是T,但我收到相同的錯誤 – plailopo
嗨 - 它有點微不足道,但它不夠完整,把它放到play.rust-lang.org並嘗試編譯它,並得到相同的錯誤,所以有點難以確定。 –