How to simplify Into()

175 Views Asked by At

I have this code, where XYBin is a superset of Bin:

impl Into<Bin> for XYBin {
    fn into(self) -> Bin {
         Bin {
            packets_tx: self.packets_tx, 
            octets_tx: self.octets_tx, 
            packets_rx: self.packets_tx, 
            octets_rx: self.octets_rx, 
            packets_rx_on_only: self.packets_rx_on_only, 
            octets_rx_on_only: self.octets_rx_on_only, 
            packets_rx_on: self.packets_rx_on, 
            octets_rx_on: self.octets_rx_on
        }
    }
}

Is there a way of using punning, or another approach (except macros) to reduce the repetitive code?

1

There are 1 best solutions below

2
On

What I had before was:

#[derive(sqlx::FromRow, Debug)]
struct XYBin { 
    x: f64,
    y: f64,
    packets_tx: i64,
    octets_tx: i64,
    packets_rx: i64,
    octets_rx: i64,
    packets_rx_on_only: Vec<i64>,
    octets_rx_on_only: Vec<i64>,
    packets_rx_on: Vec<i64>,
    octets_rx_on: Vec<i64>
}
 
impl Into<Bin> for XYBin {
    fn into(self) -> Bin {
         Bin {
            packets_tx: self.packets_tx, 
            octets_tx: self.octets_tx, 
            packets_rx: self.packets_rx, 
            octets_rx: self.octets_rx, 
            packets_rx_on_only: self.packets_rx_on_only, 
            octets_rx_on_only: self.octets_rx_on_only, 
            packets_rx_on: self.packets_rx_on, 
            octets_rx_on: self.octets_rx_on
       }
    }
}
 
#[derive(Debug, Serialize)]
struct Bin {
    packets_tx: i64,
    octets_tx: i64,
    packets_rx: i64,
    octets_rx: i64,
    packets_rx_on_only: Vec<i64>,
    octets_rx_on_only: Vec<i64>,
    packets_rx_on: Vec<i64>,
    octets_rx_on: Vec<i64>
}

After reading ColonelThirtyTwo's comment, I now have:

#[derive(sqlx::FromRow, Debug)]
struct XYBin { 
    x: f64,
    y: f64,
    #[sqlx(flatten)]
    bin: Bin
}
 
impl Into<Bin> for XYBin {
    fn into(self) -> Bin {
        self.bin
    }
}
 
#[derive(sqlx::FromRow, Debug, Serialize)]
struct Bin {
    packets_tx: i64,
    octets_tx: i64,
    packets_rx: i64,
    octets_rx: i64,
    packets_rx_on_only: Vec<i64>,
    octets_rx_on_only: Vec<i64>,
    packets_rx_on: Vec<i64>,
    octets_rx_on: Vec<i64>
}