Redundancy in function imports

Viewed 45

I think there is some redundancy in my import but I cant really figure out another way to do it

main.rs

mod lib; 
use lib::calc::med_calc;


fn main() {
    let mut numbers = vec![1,21,22,4,2];
    med_calc(& mut numbers)
}

to me it seems weird to declare the lib.rs as a module and only then I can use the structs/functions within. Since I've already declared them as modules and public in lib.rs itself.

lib.rs

pub mod calc {
    pub fn med_calc(vector: & mut Vec<u8>){
        vector.sort();
        println!("{}", vector[vector.len()/2])
    }
}

file tree (used in cargo):

src -
    |- main.rs
    |- lib.rs
1 Answers

When you have both a lib.rs and main.rs file in your project, the lib.rs file creates a library crate that can be accessed via the crate name in your crate's binary source files (like main.rs and bin/*.rs).

For example, if the crate is named rust_tmp, then you can do:

main.rs:

use rust_tmp::calc::med_calc;

fn main() {
    let mut numbers = vec![1, 21, 22, 4, 2];
    med_calc(&mut numbers)
}

No need for a mod lib;. Actually, a mod lib; is counterproductive to how lib.rs is meant to be used.

Related