Search code examples
rustrust-cargorust-tokio

How do I use public functions from Rust files within other files


I am new to rust and trying to figure out how to structure my projects in such a way I can use reusable components.

As an example I created a test project space using cargo new test

I created a concat_strings.rs , time_request.rs and start_listen.rs files.

concat_strings

pub fn concatenate_strings(strings: &[&str]) -> String {
    let mut result = String::new();
    for s in strings {
        result.push_str(s);
        result.push(' ');
    }
    result.trim_end().to_string()
}

time_request

use chrono::{Local, Datelike, Timelike};

pub fn get_current_time() -> String {
    let current_time = Local::now();
    let formatted_time = format!(
        "{:04}-{:02}-{:02}/{:02}:{:02}:{:02}",
        current_time.year(),
        current_time.month(),
        current_time.day(),
        current_time.hour(),
        current_time.minute(),
        current_time.second(),
    );
    formatted_time
}

and the idea was that I can use concat_strings from start_listen

use std::fs::File;
use std::io::Read;
use toml::Value;

mod start_listen;

pub fn start_listen() -> String {
    let mut file = File::open("Listen.toml").unwrap();
    let mut contents = String::new();
    file.read_to_string(&mut contents).unwrap();
    let value = contents.parse::<Value>().unwrap();

    let ip = value["ip"].as_str().unwrap();
    let port = value["port"].as_integer().unwrap() as u16;
}

While I can use the mod keyword just fine from main.rs it seems I cannot use it from other files.

mod concat_strings;
mod time_request;
mod start_listen;

fn main() {

Can anyone familiar with rust point out how to go about this? Thanks!

EDIT:

Doing this worked use crate::concat_strings;


Solution

  • The way I would go about this is to create a lib.rs file:

    //! This is the lib.rs file
    pub mod start_listen;
    pub mod concat_strings;
    pub mod time_request;
    
    

    and then from main.rs

    use project_name::start_listen::start_listen;
    use project_name::concat_strings::concatenate_strings;
    use project_name::time_request::get_current_time;
    
    fn main() {
        start_listen();
        concatenate_strings(&["Hey", "Hiya"]);
        let time = get_current_time();
    }
    

    and from other files (for example you want to use concatenate_string() from start_listen.rs

    use crate::concat_strings::concatenate_strings;
    
    pub fn start_listen() -> String {
        concatenate_strings(&["A string", "Also a string"]);
        do_stuff!()
    }
    

    You could refer to the Rust book Chapter 7 for more

    https://rust-book.cs.brown.edu/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html