Does Rust support compile-fail tests?

Hey everyone,

I was wondering if it's possible to write a "compile-fail test", i.e. a small #[test] that should fail to compile.

This is mostly because I'm implementing a container type that returns an iterator which shouldn't outlive its corresponding container and for that, I use PhantomData<&'a T> but there was recently a PR that attempts to remove it which breaks that invariant.

1 Like

Not directly, unfortunately, but there's a crate for that which provides the basics of such functionality.

2 Likes

I generally prefer trybuild to compiletest-rs nowadays.

It's also possible to mark doctests as compile_fail to require that they fall to compile, though that's typically not that useful of a test (since the ability to actually check what the error is is relatively small).

4 Likes

Thank you for the recommendations!

I'll start looking into how to integrate this into my project.

You can do it with compile_fail in rustdoc: https://doc.rust-lang.org/stable/rustdoc/documentation-tests.html#attributes

3 Likes

Oh, that's pretty nice, thanks for the recommendation.