Rust Cargo 依赖项

520 阅读3分钟

在Rust语言中,使用Cargo作为包管理器和构建工具,可以通过修改项目的Cargo.toml文件来指定依赖项。

常用操作:

添加依赖: 在Cargo.toml文件的[dependencies]部分添加依赖项。例如,如果想添加serde库作为依赖项:

[dependencies]
serde = "1.0"

指定版本: 可以指定依赖的版本范围。例如,只允许使用1.0.1版本:

[dependencies]
serde = "1.0.1"

使用特性(Features) : 某些依赖项提供了特性,可以通过指定特性来启用它们。例如,使用serdederive特性:

[dependencies]
serde = { version = "1.0", features = ["derive"] }

使用git仓库作为依赖: 如果依赖项还没有发布到crates.io,可以使用git仓库作为依赖:

    [dependencies]
    some_crate = { git = "https://github.com/user/some_crate.git" }

路径依赖: 如果项目结构是工作空间,并且你想依赖同一工作空间中的其他包,可以使用路径依赖:

[dependencies]
another_crate = { path = "../another_crate" }

依赖的版本兼容性: 使用~符号可以指定一个兼容的版本范围,例如:

[dependencies]
serde = "~1.0.90"

排除特定依赖: 如果你需要排除特定版本的依赖项,可以使用exclude字段:

[dependencies]
serde = { version = "1.0", exclude = "serde_json" }

可选依赖: 如果的项目有可选特性,可以使用optional = true来标记依赖项,然后在Cargo.toml[features]部分定义特性:

[features]
default = []
optional_feature = ["optional_crate"]
    
[dependencies]
optional_crate = { version = "0.1", optional = true }

使用包的特定分支或提交: 如果需要依赖特定分支或提交的代码,可以指定branchrev

[dependencies]
some_crate = { git = "https://github.com/user/some_crate.git", branch = "develop" }

依赖的元数据: 可以添加元数据来描述依赖项,例如许可证信息:

[dependencies]
some_crate = { version = "0.1", license = "MIT" }

版本依赖

在 Cargo.toml 中有一个 [denpendencies] 节点,指定需要 crate 的名称以及版本,其中有些约定(在 rust 中使用了一个叫 semver 库来处理,原单词:Semantic version,翻译成:语义化版本标准,最全原文:Semantic version parsing and comparison,我这理解为语义化的版本解析和比较)。

crate 中有主要,次要,补丁来组成版本,比如 md5 ="0.6.1", 表示现在的版本在第六个次要版本,第 1 个补丁。

不加任何符号指定

md5 = "0"     # [0.0.0 -- <1.0.0]
md5 = "0.6"   # [0.6.0 -- <0.7.0]
md5 = "0.6.1" # [0.6.1 -- <0.7.0]

接受任何新版本

md5 = "*" 

^ 符号

插入符,从左往右数,如果是 0 就往下一个版本号找,一直(总共就三个)找到一个非 0 的然后 + 1,如果一直没找到,就在指定的位置上 + 1(不包含)

md5 = "^1.2.3"  # >=1.2.3 <2.0.0
md5 = "^0.2.3"  # >=0.2.3 <0.3.0
md5 = "^0.0.3"  # >=0.0.3 <0.0.4
md5 = "^0.0"    # >=0.0.0 <0.1.0
md5 = "^0"      # >=0.0.0 <1.0.0

只接受最小范围的版本

md5 = "~0"   # [0.0.0---1.0.0 (不包含)]
md5="~0.6"   # [0.6.0---0.7.0 (不包含)]
md5="~0.6.1" # [0.6.0---0.7.0 (不包含)]

第二和第三个是一样的,因为补丁版本已经是最低的

限制大范围版本

md5 = ">0.6.1"  # 最低版本 0.6.2
md5 = ">=0.6.1" # 最低版本 0.6.1
md5 = "=0.6.1"  # 锁定版本 0.6.1

其他

在依赖中有很多不可预发的出现一些问题

  • 循环依赖
  • 不同 crate 依赖的版本库不同
  • 不同平台(操作系统)不同依赖
  • 不同环境(开发,测试,生产)不同依赖