【问题标题】:Using Option<T> with Diesel's Insertable trait将 Option<T> 与 Diesel 的 Insertable 特征一起使用
【发布时间】:2019-09-15 11:06:59
【问题描述】:

我有以下型号:

use diesel::prelude::*;

use crate::schema::category;

#[derive(Debug, Identifiable, Queryable)]
#[table_name = "category"]
pub struct Category {
    pub id: i64,
    pub name: String,
    pub description: String,
    pub parent_id: Option<i64>,
}

#[derive(Debug, Insertable)]
#[table_name = "category"]
pub struct NewCategory<'a> {
    pub name: &'a str,
    pub description: &'a str,
    pub parent_id: &'a Option<i64>,
}

和 schema.rs:

table! {
    category (id) {
        id -> Integer,
        name -> Text,
        description -> Text,
        parent_id -> Nullable<Integer>,
    }
}

但是,当我尝试编译此代码时,出现以下错误:

error[E0277]: the trait bound `std::option::Option<i64>: diesel::Expression` is not satisfied
  --> src/models/categories.rs:15:17
   |
15 | #[derive(Debug, Insertable)]
   |                 ^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `std::option::Option<i64>`
   |
   = note: required because of the requirements on the impl of `diesel::Expression` for `&std::option::Option<i64>`

error[E0277]: the trait bound `std::option::Option<i64>: diesel::Expression` is not satisfied
  --> src/models/categories.rs:15:17
   |
15 | #[derive(Debug, Insertable)]
   |                 ^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `std::option::Option<i64>`
   |
   = note: required because of the requirements on the impl of `diesel::Expression` for `&'a std::option::Option<i64>`

我需要什么才能让它工作?我环顾四周,但我发现的唯一类似问题是当某人的表中有超过 16 列时,这里不是这种情况。

【问题讨论】:

    标签: rust rust-diesel


    【解决方案1】:

    修改pub parent_id: &amp;'a Option&lt;i64&gt; 以将&amp;'a 放置在选项内:pub parent_id: Option&lt;&amp;'a i64&gt;

    【讨论】:

    • 事实上,将i64 放在引用后面是过度杀伤 IMO。我会直接使用Option&lt;i64&gt;
    • @FrancisGagné 是的,这似乎也可以正常工作。但是,我关注diesel.rs/guides/getting-started,不知道他们为什么会那样做。
    • 对字符串使用引用完全没问题。执行插入的函数不需要String 的所有权。 &amp;str 可以引用堆上或静态内存中的字符串,因此可以避免使用引用将固定字符串放在堆上。但是,i64 足够小,以至于将其放在引用后面实际上会使事情(不知不觉地)变慢。
    猜你喜欢
    • 2020-12-30
    • 2021-12-05
    • 2023-04-04
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 2018-07-08
    • 2016-05-15
    • 1970-01-01
    相关资源
    最近更新 更多