rustup update nightly
tl;dr:
❓ What is
impl_restriction?The `impl_restriction` feature allows explicit restriction of the scope in which a trait may be implemented.
The exact example from the blog post:
#![feature(impl_restriction)]
// The impl(crate) restriction prevents Foo from being implemented outside the current crate.
pub impl(crate) trait Foo {
fn method();
}
And yes, it was possible before via sealed trait pattern (https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed).
The
impl_restriction approach has two pros:1. Cleaner code without workarounds.
2. The compiler can produce better error messages when the developer tries to implement such trait outside its crate
❓ What is
mut_restriction?The mut_restriction feature allows explicit restriction of the scope in which a field may be mutated.
Also an example from the blog post:
#![feature(mut_restriction)]
pub struct Bar {
// mut(self)
pub mut(crate) alpha: u8,
}
The
mut_restriction feature can also be used with fields of enum variants and unions. Where this feature may be helpful:1. You no longer need to define a getter method. When the field can be mutated only inside
self, then it's safe to access this field directly (because it cannot be mutated from the outside).2. Preserve an invariant: we can disallow unrestricted construction with struct expressions. The compiler will throw an error when you try to create a
struct using a struct expression outside the specified scope.3. Let me just cite the blog post:
It can also work better with the borrow checker, which can track borrows at the field level and allow disjoint fields to be borrowed independently.
More info:
🟡 RFC: https://rust-lang.github.io/rfcs/3323-restrictions.html
🟣 Tracking issue: https://github.com/rust-lang/rust/issues/105077