Combining doctests and `extern crate`

299 views Asked by At

In Rust 2018 I can use extern self as crate_name and then use fully-qualified syntax, for example

extern crate self as crate_name; //set our crate name
pub struct Member;
fn test() { 
    ::crate_name::Member; //use fully-qualified name
}

However I can't seem to make it work in a doctest:

/// ```
/// extern crate self as crate_name; //set the crate name
/// pub struct Member;
/// fn test() { 
/// ::crate_name::Member; //use fully-qualified name
/// }
/// ```
fn example() { }

error[E0425]: cannot find value Member in module crate_name

I should mention that I am actually doctesting a procmacro. That is, a) the test needs to contain fully-qualified syntax, since the procmacro expands to that, b) I need to adjust the test prelude so that the expansion will compile. Basically the doctest should mock the types/paths so the procmacro can work.

1

There are 1 answers

0
Drew On BEST ANSWER

This is because as described here if fn main() doesn't appear in the doctest, rustdoc will wrap the test inside a main, so the mocked types are actually declared inside this function..

Including a main function in the test opts out of this and allows control of where the types are declared

/// ```
/// extern crate self as crate_name; //pretend we're some crate
/// pub struct Member;
/// fn main() { ::crate_name::Member; //demo fully-qualified name
/// }
/// ```
fn example() { }