Cargo test "fails due to cannot find function"

I'm new to rust, so I dont't know if I did something wrong, or this is a bug.

I tried to run the the test for the documention like descirbed here

/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, add_one(five));
/// ```
pub fn add_one(x: i32) -> i32 {
x + 1
}

but I got this error

---- src\lib.rs - add_one (line 9) stdout ----
            error[E0425]: cannot find function `add_one` in this scope
     --> <anon>:4:15
      |
    4 | assert_eq!(6, add_one(five));
      |               ^^^^^^^ not found in this scope

Used cargo version "cargo 0.20.0 (a60d185c8 2017-07-13)"

I got the problem fixed for me. I needed to add the library (project) name in-front of the function in the comment e.g. myproject::add_one(five). So I guess the sample in the documentation here Listing 14-1 is not totally correct. The snippet below now works for me like expected.

src/lib.rs

/// Adds one to the number given.
///
/// # Examples
///
/// ```
///
/// let five = 5;
///
/// assert_eq!(6, myproject::add_one(five));
/// ```

pub fn add_one(x: i32) -> i32 {
    x + 1
}

Is your code wrapped in mod tests or something like that? That's not shown in Listing -14.1.

I think you can also use super::add_one.

No its not.
What I did was.

cargo new mysample
I opened the the src/lib.rs and copied listing 14-1 into it and started cargo test. Thats all.

super::add_one does not help. It works only with mysample::add_one

Yep, there's an issue for this, we just haven't had time to fix it yet :slight_smile:

It's great that the error got fixed in the book, but isn't this a error of cargo and not of the book? I ran into this today and this question is now the top result on Google:

mod foo {
     mod bar {
         /// ```
         /// assert_eq!(return_five(), 5);
         /// ```
         fn return_five() -> usize { 5 }
     }
}

This does not compile because it can't find the function. I tried:

use self::return_five; // doesn't work
use foo::bar::return_five; // doesn't work
use crate_name::return_five; // doesn't work
use crate_name::foo::bar::return_five; // doesn't work because module is private

So how is this feature (aside from the example in the book) supposed to work? Is doc-testing private functions or functions in private modules possible - and if yes, how?

1 Like