是否可以将单个 rust 文件作为脚本运行,同时链接到其他库而不生成货物项目

Avn*_*arr 6 rust rust-cargo

我想运行一个一次性的 Rust“脚本”,而不需要为单次运行创建一个货物项目(因为我向同事提供了这个脚本)。

理想情况下,我可以直接使用命令行构建,避免创建货物项目等。

例如:

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

我需要依赖serde_json和 my some_private_packege_i_own_locally_in_another_directory

(有点类似于 Rust Playground,我想是一次性使用的)

从命令行中执行类似的操作会很棒:

rustc /path/to/main.rs --dependency serde_json, my_package ...
Run Code Online (Sandbox Code Playgroud)

Ibr*_*med 4

您可以使用 withextern标志指定依赖项,并且可以使用 指定传递依赖项的位置-L dependency。您必须手动编译每个依赖项及其所有依赖项:

// 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
Run Code Online (Sandbox Code Playgroud)

正如您所知,即使有两个直接依赖关系,这也会变得非常困难。相反,您可以使用cargo-script,它会为您处理所有这些:

cargo install cargo-script
cargo script -D hyper -D serde_json script.rs
Run Code Online (Sandbox Code Playgroud)