Series: The Rust Annals
Vol. I Issue 47 nlopes.dev
Announcing Rust 1.46.0
Expanded const evaluation and stable caller tracking make this a significant language and diagnostics release.
Rust 1.46 substantially expands what const fn can compute by adding control flow, loops, boolean operators, and array-to-slice casts. It also stabilizes #[track_caller] for panic diagnostics, makes std::mem::forget usable in const contexts, and adds two standard-library APIs.
const fn gains control flow, loops, and slice casts
The release’s largest group of changes enables several core language features inside a const fn:
if,if let, andmatchwhile,while let, andloop- the
&&and||operators
Arrays can also be cast to slices:
const fn foo() {
let x = [1, 2, 3, 4, 5];
// cast the array to a slice
let y: &[_] = &x;
}
Although these constructs were already available outside const fn, allowing them during constant evaluation adds substantial compile-time computation power. The const-sha1 crate, for example, can compute SHA-1 hashes at compile time; using it led to an observed 40x performance improvement in Microsoft’s WinRT bindings for Rust.
track_caller lets panic helpers report their caller
Rust 1.42 introduced better panic locations for unwrap and related functions using an implementation that was not yet stable. Rust 1.46 stabilizes that feature as #[track_caller], originally proposed in RFC 2091 in July 2017.
A function such as unwrap previously needed no caller-tracking annotation:
pub fn unwrap(self) -> T {
match self {
Some(val) => val,
None => panic!("called `Option::unwrap()` on a `None` value"),
}
}
Adding the attribute is the only required source change:
#[track_caller]
pub fn unwrap(self) -> T {
match self {
Some(val) => val,
None => panic!("called `Option::unwrap()` on a `None` value"),
}
}
When an annotated function panics, the default panic formatter uses the function’s caller as the location in its error message. Authors of custom panic hooks can access the same information through the std::panic::Location::caller method.
The standard library adds two APIs and another const function
std::mem::forget is now a const fn. Two additional APIs are newly stable: