相关疑难解决方法(0)

使用柴油的通用功能会导致溢出

我有一个用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)

generics rust

5
推荐指数
1
解决办法
231
查看次数

如何定义函数类型参数(或其关联类型)的函数局部类型别名?

我有一个通用函数foo具有一些复杂的特征边界:

\n\n
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}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我现在需要<C as Index<u32>>::Output在函数内部使用一堆类型(例如通过::PI或说获取 \xcf\x80 ::from_f32(3.0))。但这种类型手动输入很长,并且使整个代码非常冗长且难以阅读。(笔记:在我的真实代码中,实际类型甚至更长、更难看。)

\n\n

为了解决这个问题,我尝试创建一个函数本地类型别名:

\n\n
// Inside of `foo`:\ntype Floaty = <C as Index<u32>>::Output;\n
Run Code Online (Sandbox Code Playgroud)\n\n

但这会导致以下错误:

\n\n
use std::ops::Index;\n\n// This trait is just as an example\ntrait Float {\n    const PI: …
Run Code Online (Sandbox Code Playgroud)

rust type-alias

5
推荐指数
2
解决办法
3009
查看次数

如何通过抽象将使用 Diesel 的多个功能合二为一?

我有以下两个功能:

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)

generics types traits rust rust-diesel

1
推荐指数
1
解决办法
691
查看次数

标签 统计

rust ×3

generics ×2

rust-diesel ×1

traits ×1

type-alias ×1

types ×1