Avba
Avba

Reputation: 15296

Is it possible to run a single rust file as a script while linking to other libraries without generating cargo projects

I'd like to run a one off rust "script" without going through creating a cargo project for a single run (since I am providing this script to colleagues).

Ideally I could build directly with the command line avoiding creating cargo projects etc.

for instance:

use serde_json::Value;
use some_private_packege_i_own_locally_in_another_directory;
fn main() {
  // do some stuff with these packages and die
}

I would need to depend on the serde_json and my some_private_packege_i_own_locally_in_another_directory.

(A bit similar to rust playground I suppose for a single time use)

Something similar to this from the command line would be great:

rustc /path/to/main.rs --dependency serde_json, my_package ...

Upvotes: 6

Views: 7001

Answers (1)

Ibraheem Ahmed
Ibraheem Ahmed

Reputation: 13568

You can specify a dependency with with extern flag, and you can specify the location of transitive dependencies, with -L dependency. You will have to compile each dependency, and all of it's dependencies manually:

// compile all of serde's dependencies
// compile all of hyper's dependencies
// compile serde
// compile hyper
rustc script.rs --crate-type bin -L dependency=~/tmp/deps --extern serde_json=~/tmp/deps/serde_json.rlib --extern hyper=~/tmp/deps/hyper.rlib

As you can tell, this would get very difficult, even with two direct dependencies. Instead, you can use cargo-script, which handles all of this for you:

cargo install cargo-script
cargo script -D hyper -D serde_json script.rs

Upvotes: 4

Related Questions