Can anyone spot what I need to change to get this to compile. I'm still learning rust and this is just some code for an exercise I'm doing where I'm trying to parse some revenue and expense tables and add them. I want to store the data in these DataTable structs and I'm trying to implement the Add trait. I've successfully done so for DataRow. Just can't figure out what I need to include to get past the compiler error.
The error occurs when trying to map over the rows and add them with the + operator. Its strange because i HAVE successfully implemented the Add trait for DataRow. There is a working test included. Why doesn't the compiler recognize the Add impl?
#[derive(Debug, Eq, PartialEq)]
pub struct Header {
pub names: Vec<String>,
}
#[derive(Debug, Eq, PartialEq)]
pub struct DataRow<T> {
pub name: String,
pub data: Vec<T>,
}
impl<T> DataRow<T> {
pub fn new(name: String, data: Vec<T>) -> Self {
DataRow { name, data }
}
}
use std::ops::Add;
impl<T: Add<Output = T> + Copy> Add for DataRow<T> {
type Output = DataRow<T>;
fn add(self, other: DataRow<T>) -> Self::Output {
DataRow::new(
self.name,
self
.data
.iter()
.zip(other.data.iter())
.map(|(&item, &otheritem)| item + otheritem)
.collect(),
)
}
}
#[test]
fn testaddrows() {
let r1 = DataRow::new("asdf".to_string(), vec![1, 2, 3]);
let r2 = DataRow::new("asdf".to_string(), vec![1, 2, 3]);
assert_eq!(r1 + r2, DataRow::new("asdf".to_string(), vec![2, 4, 6]));
}
pub struct DataTable<T> {
pub header: Header,
pub rows: Vec<DataRow<T>>,
}
impl<T> DataTable<T> {
pub fn new(header: Header, rows: Vec<DataRow<T>>) -> Self {
DataTable { header, rows }
}
}
impl<T: Add<Output = T>> Add for DataTable<T> {
type Output = DataTable<T>;
fn add(self, other: DataTable<T>) -> Self::Output {
DataTable::new(
self.header,
self
.rows
.iter()
.zip(other.rows.iter())
.map(|(&row, &otherrow)| row + otherrow)
.collect(),
)
}
}