Home > OS >  Using insert-many with generics in rust
Using insert-many with generics in rust

Time:07-10

While writing a wrapper for insert-many, I wanted to add generic T to accept any struct as input of function.

But doing this gives the error "the method insert_many exists fro struct mongodb::Collection", but its trait bounds were not satisfied..."

pub async fn insert<T>(&self, docs: Vec<T>, col_name: String, options: InsertManyOptions) {
    self.db
        .collection::<T>(&col_name)
        .insert_many(docs, options);
}

How should I go forward implementing this, and what is the meaning of this error in this context?

EDIT:

"T: api::task::_::_serde::Serialize"

This was there, but somehow I got confused because of the weird path it was using instead of the global serde crate.

CodePudding user response:

Generics in Rust work different than in C . While in C it's a simple code replacement, in Rust you have to annotate what capabilities the generic has to fulfill. And only if you annotate the capabilities are you allowed to use them inside the function.

In your case, according to the mongodb::Collection documentation, the function insert_many only exists if T implements the Serialize trait. That means, you have to specify that the generic T does so.

use serde::Serialize;

// ...

pub async fn insert<T>(&self, docs: Vec<T>, col_name: String, options: InsertManyOptions)
where
    T: Serialize,
{
    self.db
        .collection::<T>(&col_name)
        .insert_many(docs, options);
}

Disclaimer #1: You need to add serde as a dependency in your Cargo.toml.

Disclaimer #2: Due to the missing context I did not actually test the code.

  • Related