1

If I have this function in src/test.rs

pub fn print_something(){
    println!("Something");
}

how can I call it in the example/test.rs ?

I've tried with extern crate, mod, use but none of these worked.

1 Answer 1

4

First, you have to declare the test module in src/lib.rs:

pub mod test;

Then, inside examples/test.rs, just use it as a library:

crate_name::test::print_something(); // Replace `crate_name` by the crate name
Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to avoid using the actual crate name? I tried crate:: and that didn't work.
@srgsanky No, you cannot, because it is a different crate? But why would you want that?
After reading Chapter 7 of the rust book (doc.rust-lang.org/book/…), I now understand that example/test.rs and src/test.rs in this example are different crates. example/test.rs is a binary crates in this package. src/lib.rs and src/test.rs is part of the library crate in this package. A binary crate can use the paths in the library create only via the <crate_name>. The literal crate can be used only when trying to refer to modules within the same crate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.