Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redundancy in function imports

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading