Using generic structs with Insertable
#4446
-
I want to create a struct that can be parametrized such that I can create two versions on need - one that owns strings and one that borrows them. Here's a first implementation: use std::borrow::Borrow;
use diesel::prelude::*;
diesel::table! {
foo (id) {
id -> Int4,
name -> Text,
}
}
#[derive(Insertable)]
#[diesel(table_name = foo)]
#[diesel(check_for_backend(diesel::pg::Pg))]
struct NewFoo<Str: Borrow<str>> {
name: Str
}
fn main() {
let new_foo = NewFoo { name: String::new() };
} this fails to compile, throwing the following error:
Okay, simple. Just add another trait bound, as the compiler suggests (relevant snippet shown): #[derive(Insertable)]
#[diesel(table_name = foo)]
#[diesel(check_for_backend(diesel::pg::Pg))]
struct NewFoo<Str: Borrow<str> + diesel::Expression<SqlType = diesel::sql_types::Text>> {
name: Str
} this now fails to compile as well:
I also tried using the following trait bounds (separately), both returning the first error:
this discussion seems to suggest that what I'm trying to do isn't even possible. Is that correct? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The following definition works: #[derive(Insertable)]
#[diesel(table_name = foo)]
#[diesel(check_for_backend(diesel::pg::Pg))]
struct NewFoo<Str: AsExpression<diesel::sql_types::Text>>
where
for<'a> &'a Str: AsExpression<diesel::sql_types::Text>,
{
name: Str,
} We require bounds for the owned type and for the reference type as the insertable derive generates implementations for both |
Beta Was this translation helpful? Give feedback.
The following definition works:
We require bounds for the owned type and for the reference type as the insertable derive generates implementations for both
NewFoo
and&NewFoo
.