我有一个用Rust编写的API,它的目标是在数据库中公开~15个表.我已经编写了几个非常相似的函数来公开每个表,所以我认为我会对多态性进行破解以简化代码.
我已将所有代码缩减为单个文件:
#[macro_use]
extern crate diesel;
extern crate dotenv;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
table! {
table1 (id) {
id -> Int4,
value -> Text,
}
}
table! {
table2 (id) {
id -> Int4,
value -> Text,
}
}
#[derive(Identifiable, Queryable, Serialize)]
#[table_name = "table1"]
struct Model1 {
pub id: i32,
pub value: String,
}
#[derive(Identifiable, Queryable, Serialize)]
#[table_name = "table2"]
struct Model2 {
pub id: i32,
pub value: String,
}
use dotenv::dotenv;
use …Run Code Online (Sandbox Code Playgroud) 我有一个通用函数foo具有一些复杂的特征边界:
use std::ops::Index;\n\n// This trait is just as an example\ntrait Float {\n const PI: Self;\n fn from_f32(v: f32) -> Self;\n}\n// impl Float for f32, f64 ...\n\nfn foo<C>(container: &C)\nwhere\n C: Index<u32>,\n <C as Index<u32>>::Output: Float,\n{\n // ...\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我现在需要<C as Index<u32>>::Output在函数内部使用一堆类型(例如通过::PI或说获取 \xcf\x80 ::from_f32(3.0))。但这种类型手动输入很长,并且使整个代码非常冗长且难以阅读。(笔记:在我的真实代码中,实际类型甚至更长、更难看。)
为了解决这个问题,我尝试创建一个函数本地类型别名:
\n\n// Inside of `foo`:\ntype Floaty = <C as Index<u32>>::Output;\nRun Code Online (Sandbox Code Playgroud)\n\n但这会导致以下错误:
\n\nuse std::ops::Index;\n\n// This trait is just as an example\ntrait Float {\n const PI: …Run Code Online (Sandbox Code Playgroud) 我有以下两个功能:
pub fn get_most_recent_eth_entry(conn: &SqliteConnection) -> Result<i32, Error> {
let res = types::ethereum::table
.order(types::ethereum::time.desc())
.limit(1)
.load::<types::ETHRecord>(&*conn);
match res {
Ok(x) => {
if x.len() > 0 {
Ok(x.get(0).unwrap().time)
} else {
Ok(0)
}
}
Err(err) => Err(format_err!("Error here! {:?}", err)),
}
}
pub fn get_most_recent_btc_entry(conn: &SqliteConnection) -> Result<i32, Error> {
let res = types::bitcoin::table
.order(types::bitcoin::time.desc())
.limit(1)
.load::<types::BTCRecord>(&*conn);
match res {
Ok(x) => {
if x.len() > 0 {
Ok(x.get(0).unwrap().time)
} else {
Ok(0)
}
}
Err(err) => Err(format_err!("Error here! {:?}", …Run Code Online (Sandbox Code Playgroud)