Urgent.News

What's breaking now, across thousands of outlets.

Tech

Restricting trait implementability and field mutability

RFC 3323, titled "Restrictions", is now available for testing on Rust's nightly development channel. This post will provide a brief overview of the two key features introduced: impl_restriction and mut_restriction.

The impl_restriction feature enables developers to limit the scope in which a trait can be implemented. For instance, if a trait Foo has a method intended for internal use only, the scope can be restricted to its defining crate. This is accomplished using the `impl(crate)` syntax. While this approach is akin to employing a sealed trait pattern, it offers a more straightforward alternative.

The feature also facilitates the compiler to generate clearer error messages when an implementation is attempted outside the allowed scope.

Similarly, the mut_restriction feature controls the mutability of a struct's field within a specific scope. Consider an example where struct Bar has a mutable field alpha confined to its defining crate. By using `mut(crate)`, the mutation of alpha is restricted to within the crate where Bar is defined. This feature serves as an alternative to getter methods, enabling read-only access via direct field access.

Furthermore, it aligns well with Rust's borrow checker, which can manage field-level borrows and permit independent borrowing of disjoint fields.

Attempting to mutate a restricted field outside its permitted scope will trigger a direct error message from the compiler. The mut_restriction feature can also be applied to enum variants and unions. However, struct expressions are prohibited if any mut-restricted field cannot be mutated from the current scope to prevent the creation of potentially invalid values.

Feedback on these new features is highly encouraged. To begin, use the latest Rust nightly compiler and enable the respective feature through the `#![feature(impl_restriction)]` or `#![feature(mut_restriction)]` attribute. Share your insights and concerns regarding the syntax, as it remains open to discussion. These features were developed as part of a Google Summer of Code 2026 project, and the mentors, Jacob Pratt and Urgau, are thanked for their invaluable guidance and support.

Ensure that rustup is updated to the latest nightly version before attempting to utilize these features.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at blog.rust-lang.org →

More in Tech

More from Monday 10 August →