Can't find scope for library rustdoc examples

I'm struggling to get a rustdoc example at the top level of a my library to compile.

To demonstrate the issue, I can create a new library cargo init --lib test_lib, then edit src/lib.rs as follows:

/// Test Library
///
/// # Example
///
/// ```
/// let t = Foo{ a: 2, b: 3 };
/// ```

pub struct Foo {
    a : i32,
    b : i32,
}

Now when I try rustdoc --test src/lib.rs, I get the error "Foo... not found in this scope". I've tried variations on use crate::Foo, etc in the example code but I'm not making any progress and haven't found a similar forum question. Appreciate any help.

Doc tests use your library like a dependency. So this is closer:

/// ```
/// use test_lib::Foo;
/// let t = Foo { a: 2, b: 3 };
/// ```
pub struct Foo {
    a: i32,
    b: i32,
}

But this will still fail as-is because fields a and b are private.

1 Like

Thank you @quinedot!

I had tried something like this on my real code and fortunately I can reproduce the problem on this simple example.

I updated the above lib.rs example to:

/// Test Library
///
/// # Example
///
/// ```
/// use test_lib::Foo;
/// let t = Foo{ a: 2, b: 3 };
/// ```

pub struct Foo {
    pub a : i32,
    pub b : i32,
}

...and now when I run rustdoc --test src/lib.rs, I get the error below, which I haven't been able to make progress on:

running 1 test
test src/lib.rs - Foo (line 6) ... FAILED

failures:

---- src/lib.rs - Foo (line 6) stdout ----
error[E0463]: can't find crate for `lib`
 --> src/lib.rs:5:1
  |
2 | extern crate r#lib;
  | ^^^^^^^^^^^^^^^^^^^ can't find crate

error[E0432]: unresolved import `test_lib`
 --> src/lib.rs:7:5
  |
4 | use test_lib::Foo;
  |     ^^^^^^^^ maybe a missing crate `test_lib`?

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0432, E0463.
For more information about an error, try `rustc --explain E0432`.
Couldn't compile the test.

failures:
    src/lib.rs - Foo (line 6)

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.09s

Here is the Cargo.toml, just to verify the library name is just test_lib:

[package]
name = "test_lib"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

Oh, I was thinking of running

cargo test --doc

If I run

cargo test --doc -v

I can see it runs

rustdoc --edition=2021 --crate-type lib --crate-name test_lib \
  --test /.../test_lib/src/lib.rs \
  -L dependency=/.../test_lib/target/debug/deps \
  -L dependency=/.../test_lib/target/debug/deps \
  --extern test_lib=/.../test_lib/target/debug/deps/libtest_lib-2cdf76662efee6ed.rlib  \
  -C embed-bitcode=no \
  --error-format human

And a more minimal example that works for me is

rustdoc --edition=2021 --crate-name test_lib \
  --test src/lib.rs \
  --extern test_lib=target/debug/libtest_lib.rlib 

But probably "use cargo" is the best advice.

3 Likes