rust – 指定仅二进制依赖项

我有一个包含二进制文件和库的箱子.该库对依赖性非常轻,而二进制文件需要更多,例如,加载文件或做范围并行的事情.

目前,我的Cargo.toml设置如下:

[dependencies.kdtree]
path = "../kdtree"

[dependencies]
rand="0.3.0"
rustc-serialize = "0.3"
csv = {git = "https://github.com/BurntSushi/rust-csv.git"}
crossbeam = "0.2"
num_cpus = "0.2"

[lib]
name = "conformal"
path = "src/lib.rs"

[[bin]]
name = "ucitest"
path = "src/bin/main.rs"

库需要的唯一依赖是kdtree和rand.但是,即使您只构建库,它似乎仍然构建了仅二进制依赖项.我已经尝试使用[[bin] .dependencies]或[ucitest-dependencies](或在[[bin]]下添加依赖项= []行)等功能和其他技巧,我认为这些技巧可能只是为二进制构建,但我找不到办法.

这些不足以使这成为一个问题,但它困扰着我.有没有办法缩小依赖关系,以便它们只为特定的二进制文件构建?

有几种方法可以模拟您想要的内容

1)将二进制文件转换为示例

Examples和测试是使用dev-dependencies构建的,因此您可以将这些依赖项移动到此部分中.图书馆不会依赖它们.

# File structure
conformal/
    Cargo.toml
    src/
        lib.rs
    examples/        # <-- the `ucitest` is
        ucitest.rs   # <-- moved to here
# Cargo.toml

[dependencies]
kdtree = { path = "../kdtree" }
rand = "0.3"

[dev-dependencies]  # <-- move the examples-only dependencies here
serde = "1"
csv = "0.15"
crossbeam = "0.3"
num_cpus = "1"

[lib]
name = "conformal"

[[example]]         # <--- declare the executable
name = "ucitest"    # <--- as an example

要运行二进制文件,请使用:

cargo run --example ucitest

2)具有所需功能的可选依赖项

依赖关系可以是optional,因此依赖于您的保形库的其他包装箱将不需要下载它们.

从Rust 1.17开始,二进制文件可以声明它们require可以打开某些可选功能,从而有效地使这些库“仅用于二进制文件”.

# Cargo.toml

[dependencies]
kdtree = { path = "../kdtree" }
rand = "0.3"

serde = { version = "1",optional = true }          # <-- make 
csv = { version = "0.15",optional = true }         # <-- all of
crossbeam = { version = "0.3",optional = true }    # <-- them
num_cpus = { version = "1",optional = true }       # <-- optional

[lib]
name = "conformal"

[features]
build-binary = ["serde","csv","crossbeam","num_cpus"]

[[bin]]         
name = "ucitest"    
required-features = ["build-binary"]     # <--

请注意,在构建二进制文件时需要手动传递–features build-binary:

cargo run --features build-binary --bin ucitest

3)将二进制文件作为自己的包

当库和二进制文件是独立的包时,您可以执行任何依赖项管理.

# File structure
conformal/
    Cargo.toml
    src/
        lib.rs
    ucitest/          # <-- move ucitest
        Cargo.toml    # <-- into its own
        src/          # <-- package.
            main.rs
# ucitest/Cargo.toml 

[dependencies]
conformal = { version = "0.1",path = "../" }   # <-- explicitly depend on the library
serde = "1"
csv = "0.15"
crossbeam = "0.3"
num_cpus = "1"

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...