The Developer
The Developer

Reputation: 379

How to remove a struct's field?

I make a request to a CouchDB database and get a response. Here's the struct for it:

use couch_rs::{types::{document::DocumentId}, CouchDocument, error::CouchResult};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, CouchDocument, Default, Debug)]
pub struct GuildEntry {
    #[serde(skip_serializing_if = "String::is_empty")]
    pub _id: DocumentId,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub _rev: String,

    pub embedColor: String
}

I want to remove _id and _rev fields, or at least create a struct instance with all of the fields, except for those two. I can't afford creating a new struct without those fields and transform it from the response, because there's going to be a lot of fields in the future.

What have I tried/looked into so far:

How can I accomplish this? Is this even possible?

Upvotes: 2

Views: 1559

Answers (1)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26589

Composition is really the only way. Though you don't have to make two separate structures for each; you can use one generic structure:

extern crate serde;

#[derive(serde::Deserialize)]
struct WithID<T> {
    id: String,
    #[serde(flatten)]
    inner: T,
}

#[derive(serde::Deserialize)]
struct Foo {
    bar: String,
    baz: String,
}

type FooWithId = WithID<Foo>;

Implementing Deref and DerefMut for WithID with Target = T would make things easier, as you won't have to reference inner as much.

Upvotes: 5

Related Questions