rust-script icon indicating copy to clipboard operation
rust-script copied to clipboard

Document how to use external modules?

Open rauschma opened this issue 2 years ago • 4 comments

Is it possible to use external modules? If yes, then it may make sense to document how.

Example:

% cat ./main.rs
mod other;

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

% cat ./other.rs 
pub fn hello() {
    println!("How are you?");
}

For comparison, cargo-play handles it like this. I can run the aforementioned two modules via cargo play *.rs

rauschma avatar Feb 12 '23 17:02 rauschma

Is it possible to use external modules?

It's not currently possible, but looks interesting. Experimenting with it.

fornwall avatar Mar 25 '23 22:03 fornwall

Related, it's possible to "include" another rust file, with something like:

include!(concat!(env!("RUST_SCRIPT_BASE_PATH"), "/utils.rs"));

call_function_defined_in_utils_rs();

It's not the same thing as modules and a bit verbose, but it can sometimes be useful.

fornwall avatar Mar 26 '23 12:03 fornwall

It is also possible to use local crates. Something like:

my_crate/src/lib.rs

pub fn hello() {
    println!("How are you?");
}

my_rust_script

#!/usr/bin/env rust-script

//! ```cargo
//! [dependencies]
//! my_crate = { path = "my_crate" }
//! ```

fn main() {
    my_crate::hello()
}

rfdonnelly avatar Apr 06 '23 00:04 rfdonnelly

Whether officially supported or not, currently both mod other; and include!("other.rs"); works. However, the thing that doesn't work, is that rust-script script.rs, does not recompile if only other.rs changed. So in that case use rust-script -f script.rs.

vallentin avatar Nov 25 '25 23:11 vallentin