【问题标题】:Compile and run rust programs without creating separate cargo projects在不创建单独的货物项目的情况下编译和运行 rust 程序
【发布时间】:2022-08-02 23:56:04
【问题描述】:

在通过Rust by Example时, 我发现自己为教程中的每个程序创建了一个新的货物项目。

这很快变得很麻烦。

我尝试的另一个策略是让我的工作目录结构如下:

src\\
    guessing_game.rs
    main.rs
    temp.rs

其中main.rs 包含

mod guessing_game;
mod temp;

/// Hello
fn main() {
    // guessing_game::play();
    println!(\"{}\", temp::is_prime(6));
}

cargo.toml 包含

[package]
name = \"rust_prog_dump\"
version = \"0.1.0\"
edition = \"2018\"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = \"0.8.4\"

我会在main() 中调用目标函数并注释掉其他函数。

我们有替代方案吗?

我见过this issueJon Cairns\' post。 我使用 Windows,因此该脚本对我不起作用。

    标签: rust


    【解决方案1】:

    我们有替代方案吗?

    一种替代方法是直接使用rustc 手动编译,但是如果您需要依赖项,这很烦人。

    另一种选择是在 crate 中有多个二进制文件,然后您可以使用 --bin 选择要编译(和运行)的二进制文件:

    > cargo new multibin
         Created binary (application) `multibin` package
    > cd multibin
    > mkdir src/bin
    > echo 'fn main() { println!("test 1"); }' > src/bin/test1.rs
    > echo 'fn main() { println!("test 2"); }' > src/bin/test2.rs
    > echo 'fn main() { println!("primary"); }' >| src/main.rs
    > cargo r
    error: `cargo run` could not determine which binary to run. Use the `--bin` option to specify a binary, or the `default-run` manifest key.
    available binaries: multibin, test1, test2
    > cargo r --bin multibin
       Compiling multibin v0.1.0 (/private/tmp/multibin)
        Finished dev [unoptimized + debuginfo] target(s) in 0.44s
         Running `target/debug/multibin`
    primary
    > cargo r --bin test1
       Compiling multibin v0.1.0 (/private/tmp/multibin)
        Finished dev [unoptimized + debuginfo] target(s) in 0.10s
         Running `target/debug/test1`
    test 1
    > cargo r --bin test2
       Compiling multibin v0.1.0 (/private/tmp/multibin)
        Finished dev [unoptimized + debuginfo] target(s) in 0.10s
         Running `target/debug/test2`
    test 2
    

    如您所见,您可以拥有一个src/main.rs,它将继承板条箱的名称,但通常如果您开始拥有多个二进制文件,则将它们全部放入src/bin

    第三种选择是使用类似cargo-script(迄今为止最方便但长期未维护且IIRC仅与2015版兼容)或runner或类似的东西(可能还有其他)。

    【讨论】:

      【解决方案2】:

      Masklinnmultiple-binary solution 与优秀的 IDE 配合使用时就像一个魅力(一键执行)。

      使用 IntelliJ 社区版 + Rust 和 TOML 插件

      1. 出现提示时选择 TOML 文件。 (仅在导入项目时)
      2. 转到项目设置 > 模块。将src/bin 标记为源文件夹。
      3. 重新启动 IDE。您将拥有Current File 作为可用的运行配置。

        使用 VS 代码 + Code Runner extension

        1. 单击出现在fn main() 上方的Run|Debug 按钮。请注意,常规的运行代码快捷方式 (Ctrl+Alt+ñ) 如果您有依赖项,则可能无法正常工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-07
        • 2012-10-22
        • 1970-01-01
        • 1970-01-01
        • 2020-07-13
        • 2011-05-02
        相关资源
        最近更新 更多