0

I’m just starting to learn Rust and have written a couple of simple test programs. I’ve now started writing a library function. This library function has two example programs that each call the same function in another file using different parameters. These two programs together with the callable function were initally all in the "examples" directory. However, using “cargo build" it failed saying that the callable function file needed a "main()" function. Eventually I created another folder “functions” under "examples" and copied the callable function to that folder, and "Cargo build" then succeeded.

The directory structure is now:
├─── format_int:
       ├─── examples:
        |      └─── test_format_int_1.rs
        |      └─── test_format_int_2.rs
        |      ├─── functions:
        |             └─── fn_test_format_int.rs                       
        ├─── src:
              └─── lib:
                      └─── format_int.rs

The example programs are identical with the exception of the parameter used. viz:

File: test_format_int_1.rs :-

#[path = "./functions/fn_test_format_int.rs"] mod fn_test_format_int;

const TF_DISPLAY: bool = false;

fn main() {  
    fn_test_format_int::fn_run(TF_DISPLAY);
}

file: fn_test_format_int.rs:

use std::str;

pub fn fn_run(tf_display: bool) {
    print!("Test formatting of integers\n");
.....

//---- CALL THE FORMAT LIBRARY FUNCTION ----//
    let s_result: String = format_int::format_int(s_mask, i_num);

I did look at other questions and answers, but I could not find anything that specifically handled the above. I also tried other possible solutions, but perhaps they were not structured correctly.

Is this the correct way to use a callable function in another file (separate folder), or is there a way to indicate to "Cargo build" that an ".rs" file contains a callable function and does not require a main() function?

Brian Oh
  • 9,604
  • 12
  • 49
  • 68
  • Does this answer your question? [Rust package with both a library and a binary?](https://stackoverflow.com/questions/26946646/rust-package-with-both-a-library-and-a-binary) – E_net4 Jul 05 '20 at 13:06
  • There is a relevant section in the Cargo book: [Package layout](https://doc.rust-lang.org/cargo/guide/project-layout.html). You should not need to employ path directives once you follow a standard layout and then use the function as belonging in the library. – E_net4 Jul 05 '20 at 13:06
  • Ok thanks, I'll check that out. – Brian Oh Jul 09 '20 at 05:30

0 Answers0