Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required to use module name twice to reference a struct in the module [duplicate]

Tags:

rust

Main function is as follow:

mod stats;

fn main() {
    let raw_data = [10, 10, 20, 1, 2, 3, 5];
    let mut v: Vec<u32> = Vec::new();
    let mean = 0;
    let median = 0;
    let mode = 0;
    for i in raw_data.iter() {
        v.push(*i);
    }
    let stat = stats::stats::Stats::new(v);
}

And module stats as follow:

pub mod stats {
    pub struct Stats {
        data: Vec<u32>,
    }
    impl Stats {
        pub fn new(data: Vec<u32>) -> Stats {
            Stats { data }
        }
        pub fn find_mean(&self) -> f64 {
            let mut sum = 0;
            for i in &self.data {
                sum += i;
            }
            return (sum / self.data.iter().count() as u32) as f64;
        }
        pub fn find_mode(&self) -> u32 {}
        pub fn find_median(&self) -> f64 {}
    }
}

Why do I have to use stats::stats to reference struct Stats.

Project Structure

like image 919
Vishnu Divakar Avatar asked Sep 15 '25 01:09

Vishnu Divakar


1 Answers

Inside your stats.rs file you create another module stats which means, that you have to use stats::stats, because every file creates its own module.

To solve your issue, just remove pub mod stats in your stats.rs file.

For further information see:

  • The book Chapter 7
  • How to I do a basic import/include of a function from one module to another in Rust 2015?
  • How do I import from a sibling module?
  • How to use functions from one file among multiple files?
  • What are the valid path roots in the use keyword?
like image 55
hellow Avatar answered Sep 16 '25 22:09

hellow