Shahar 'Dawn' Or
Shahar 'Dawn' Or

Reputation: 2961

How to allow and expect a compiler warning in Rust?

Sometimes during development I would like to allow warnings. For example, for dead_code. Yet, in CI and pre_commit git hooks, I have RUSTFLAGS="--deny warnings".

So I'm thinking that what I would like is an attribute such as

#[expect(dead_code)]
fn foo() {
    todo!();
}

It would work similar to TypesScript's @ts-expect-error and yet be more specific, expecting a specific list of warnings.

Not sure whether it would make sense for expecting errors, as well.

Upvotes: 8

Views: 660

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71565

This is supported since Rust 1.81.0. The RFC is called Lint Reasons. The form is exactly what you would expect: #[expect(lint)].

#[expect(dead_code)]
fn foo() {
    todo!();
}

Playground.

If the expectation is not fulfilled, a warning is raised. You can #[deny(unfulfilled_lint_expectations)] to make it into an error.

If you only want to allow the warning (but not warn when it is not raised), use #[allow(lint)]:

#[allow(dead_code)]
fn foo() {
    todo!();
}

Playground.

Upvotes: 10

Related Questions