TLDR at the end;
My two cents on the matter, I do not think Traits should or realistically could include fields because:
- It forces the user of a trait to maintain a field they may not want (I’ll explain forces later)
- Traits already effectively have this power without forcing it upon the user.
- Trait fields would either break the current implementation of Traits or force overhead on users.
Example of what I’m talking about:
pub struct Foo {
x: usize
}
pub trait Bar: BorrowMut<Foo> {
fn do_something_cool_with_foo(&mut self);
fn do_other_thing_with_foo(&mut self) {
//Your awesome implementation.
}
}
impl<T> Bar for T where T: BorrowMut<Foo> {}
This is valid for Traits as they currently are and, if implemented in a library crate, the functionality of Bar is provided for all types which choose to implement BorrowMut<Foo> implicitly with little to no overhead.
This implementation also effectively implements “traits with fields” by dint of the fact that before a user can make use of the Bar trait for their MyType type they must first provide some implementation to treat MyType as if it had the data of Foo.
However if Traits themselves could be made with fields either:
- Every type that wants to make use of the
Bar trait would have to implement each of the fields currently in Foo in some way, requiring they think and understand how the data should be managed.
- The
Bar trait provides implementation for initialising and managing the data already and the line “impl<T> Bar for T where T: BorrowMut<Foo> {}” would implement Bar on all types which make use of it without necessarily telling the user that there’s a memory overhead added to their MyType by using Bar or otherwise cloging up their compiler output with warnings to let them know its happening.
TLDR: Traits as they currently exist alongside Rusts borrowing can already implement “traits with fields” in an effective and user friendly way that requires a conscious decision by the user to take responsibility for any memory overhead.