所以我有这个使用
rusqlite
的代码。而且效果很好。
pub struct Database {
conn: Connection,
}
impl Database {
pub fn get(self: &Self, id: Option<u64>, name: Option<&str>) -> Result<Option<Record>, Error> {
let mut stmt = match name {
Some(_) => { self.conn.prepare_cached(Self::STMT_GET_ID_NAME) },
None => { self.conn.prepare_cached(Self::STMT_GET_ID) }
}?;
let mut rows = match name {
Some(name) => { stmt.query(params![id, name]) },
None => { stmt.query(params![id]) }
}?;
let row = rows.next()?;
if let Some(row) = row {
let record = Record {
id: row.get(0)?,
parent: row.get(1)?,
name: row.get(2)?,
record_type: row.get(3)?,
timestamp: row.get(4)?,
created_at: row.get(5)?,
modified_at: row.get(6)?,
size: row.get(7)?,
hash: row.get(8)?,
inode: row.get(9)?
};
Ok(Some(record))
} else {
Ok(None)
}
}
}
我遇到的问题是
match
语句本质上是重复的。
我尝试过类似的方法,但这行不通。
let (mut stmt, mut rows) = match name {
Some(name) => {
let mut stmt = self.conn.prepare_cached(Self::STMT_GET_ID_NAME)?;
let rows = stmt.query(params![id, name])?;
(stmt, rows)
}
None => {
let mut stmt = self.conn.prepare_cached(Self::STMT_GET_ID)?;
let rows = stmt.query(params![id])?;
(stmt, rows)
}
};
问题是编译器抱怨
stmt
的生命周期
error[E0597]: `stmt` does not live long enough
error[E0505]: cannot move out of `stmt` because it is borrowed
我真的尝试了很多东西,并尝试疯狂地谷歌搜索。但我被困住了。
是否有甚至有一种方法可以做到这一点,而不是完全丑陋和惯用?我觉得这是一个非常愚蠢的问题,而且我在这里错过了一些基本的东西......
stmt
并在比赛臂内分配给它。例如,这样编译:
let mut stmt;
let mut rows = match name {
Some(name) => {
stmt = self.conn.prepare_cached("x")?;
stmt.query(params![id, name])?
}
None => {
stmt = self.conn.prepare_cached("y")?;
stmt.query(params![id])?
}
};