I’m trying to push trait objects that implement ToSql
in a vector, and pass it as a function parameter. But I’m running into E0277, which basically says that the trait Sized
is not implemented.
use postgres::types::{IsNull, Type, ToSql}; // 0.19.7
use bytes::BytesMut;
#[derive(Debug)]
struct Field {}
unsafe impl Sync for Field {}
impl ToSql for Field {
fn to_sql<>(&self, _: &Type, _: &mut BytesMut) -> Result<IsNull, Box<(dyn std::error::Error + Send + Sync + 'static)>> { todo!() }
fn accepts<>(_: &Type) -> bool { todo!() }
fn to_sql_checked(&self, _: &Type, _: &mut BytesMut) -> Result<IsNull, Box<(dyn std::error::Error + Send + Sync + 'static)>> { todo!() }
}
fn some_action<S>(_pars: &[S])
where S: ToSql + Sync
{}
fn main() {
let mut v = Vec::<&(dyn ToSql + Sync)>::new();
let t = Field{};
v.push(&t);
some_action(&v);
}
I tried a solution from another SO-thread to no avail:
fn make_dyn<T: ToSql + Sync + ?Sized>(arg: &T) -> &(dyn ToSql + Sync) { arg }
However, another basic example actually does work, and I can’t tell why:
struct Test {}
unsafe impl Sync for Test {}
unsafe impl Send for Test {}
fn x<T>(_pars: &[T]) where T: Sync + Send {}
fn main() {
let mut v = Vec::<&(dyn Sync + Send)>::new();
let t = Test{};
v.push(&t);
x(&v);
}
Earlier on I converted the trait objects to &str
so I could toss them as SQL parameters but then I had to ask PostgreSQL to do all proper conversions with ($1::text)::bigint
which is not ideal.
How could I solve or work around this issue?