Search code examples
importmodulerustunused-variables

How can I import a single function from a module in Rust?


I'm fairly new to Rust and coming from Python there are some things that are done very differently. In Python, one can import a single function from a .py file by typing from foo import bar, but I still haven't found any equivalent in Rust.

I have the following files:

.
├── main.rs
└── module.rs

With the following contents:

main.rs

mod module;

fn main() {
    module::hello();
}

module.rs

pub fn hello() {
    println!("Hello");
}

pub fn bye() {
    println!("Bye");
}

How do I create my module or type my imports so that I don't get the following warning:

warning: function is never used: `bye`
  --> module.rs:5:1
   |
 5 |     pub fn bye() {
   |     ^^^^^^^^^^^^
   |
   = note: #[warn(dead_code)] on by default

Solution

  • There's nothing materially different from importing a module vs a type vs a function vs a trait:

    use path::to::function;
    

    For example:

    mod foo {
        pub fn bar() {}
    }
    
    use foo::bar;
    
    fn main() {
        bar();
    }