Can't use a dependent crate in Rust documentation tests

From The Rust Programming Language, first edition chapter on documentation:

Here's the full algorithm rustdoc uses to preprocess examples:

  1. Any leading #![foo] attributes are left intact as crate attributes.
  2. Some common allow attributes are inserted, including unused_variables, unused_assignments, unused_mut, unused_attributes, and dead_code. Small examples often trigger these lints.
  3. If the example does not contain extern crate, then extern crate <mycrate>; is inserted.
  4. Finally, if the example does not contain fn main, the remainder of the text is wrapped in fn main() { your_code }

Point #3 is relevant here. When you have no extern crate lines, your crate is automatically added. Once you add the first extern crate, no crates will be automatically added — that includes your crate!

You will need to add extern crate lines for both regex and rusty_nltk.


After being pointed to the docs, I solved it by wrapping a main around my code with extern crates:

/// Return a list of the offsets of the tokens in `s`, as a sequence of `(start, end)`
/// tuples, by splitting the string at each successive match of `regex`.
///
/// # Examples
///
/// To return a list of spans based on whitespaces:
///
/// ```
/// extern crate regex;
/// extern crate rusty_nltk;
/// use rusty_nltk::tokenize::util::regexp_span_tokenize;
/// use regex::Regex;
///
/// fn main() {
///   let s = "Good muffins cost $3.88\nin New York.  Please buy me
///           two of them.\n\nThanks.";
///   let regex = Regex::new(r"\s").unwrap();
///   let spans = regexp_span_tokenize(s, &regex);
/// }
/// ```

I decided to change my doc style to include mains for all examples, but if this isn't your style, you can add # before code to hide it from docs.