简体   繁体   中英

How to implement a trait for any mutability?

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 {…}

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM