7
votes

Can mutability be a generic parameter in traits? I'd like to implement a trait for a mutable and an immutable variant of a type without having to copy&paste the impl block.

trait Foo<T> {…}

impl<T> Foo for *const T {…}
impl<T> Foo for *mut T {…same thing again…}

Wishful pseudocode:

trait Foo<T> {…}

impl<T, Mutability> Foo for *Mutability T {…}
1
As a workaround, you can define a private macro to generate both impls, or you can forward one variant's implementation to the other with casts: Implement for *const T, then define the impl for *mut T as (self as *const T).method() or something like that.user395760
The casting is probably the solution I've seen the most for this case; I think I've even seen people keep * const T pointers and cast to *mut T only when explicitly needed. More generally, people want to be able to return parameterized over mutability, as well as change the mutability of references &T <-> &mut T. I'd be very wary about casting or transmuting in those cases.Shepmaster

1 Answers

7
votes

Can mutability be a generic parameter in traits?

No. ^_^

Here's some detailed discussion on the matter (Internals, Reddit).

I think in general people recognize that the current state is not ideal, but that it's not terribly constraining at the moment, either. There's concerns on exactly how it would be implemented and the soundness of various approaches. Some people wonder if Higher-Kinded Types (HKTs) would solve the problem, if and when they are added to Rust.

See also: