The Manifest Format

The Cargo.toml file for each package is called its manifest. Every manifestfile consists of one or more sections.

The [package] section

The first section in a Cargo.toml is [package].

  1. [package]
  2. name = "hello_world" # the name of the package
  3. version = "0.1.0" # the current version, obeying semver
  4. authors = ["Alice <a@example.com>", "Bob <b@example.com>"]

The name field

The package name is an identifier used to refer to the package. It is usedwhen listed as a dependency in another package, and as the default name ofinferred lib and bin targets.

The name must not be empty, use only alphanumeric characters or - or _.Note that cargo new and cargo init impose some additional restrictions onthe package name, such as enforcing that it is a valid Rust identifier and nota keyword. crates.io imposes even more restrictions, such asenforcing only ASCII characters, not a reserved name, not a special Windowsname such as "nul", is not too long, etc.

The version field

Cargo bakes in the concept of SemanticVersioning, so make sure you follow some basic rules:

  • Before you reach 1.0.0, anything goes, but if you make breaking changes,increment the minor version. In Rust, breaking changes include adding fields tostructs or variants to enums.
  • After 1.0.0, only make breaking changes when you increment the major version.Don’t break the build.
  • After 1.0.0, don’t add any new public API (no new pub anything) in patch-levelversions. Always increment the minor version if you add any new pub structs,traits, fields, types, functions, methods or anything else.
  • Use version numbers with three numeric parts such as 1.0.0 rather than 1.0.

The authors field (optional)

The authors field lists people or organizations that are considered the"authors" of the package. The exact meaning is open to interpretation — it maylist the original or primary authors, current maintainers, or owners of thepackage. These names will be listed on the crate's page oncrates.io. An optional email address may be included within angledbrackets at the end of each author.

The edition field (optional)

You can opt in to a specific Rust Edition for your package with theedition key in Cargo.toml. If you don't specify the edition, it willdefault to 2015.

  1. [package]
  2. # ...
  3. edition = '2018'

The edition key affects which edition your package is compiled with. Cargowill always generate packages via cargo new with the edition key set to thelatest edition. Setting the edition key in [package] will affect alltargets/crates in the package, including test suites, benchmarks, binaries,examples, etc.

The build field (optional)

This field specifies a file in the package root which is a build script forbuilding native code. More information can be found in the build scriptguide.

  1. [package]
  2. # ...
  3. build = "build.rs"

This field specifies the name of a native library that is being linked to.More information can be found in the links section of the buildscript guide.

  1. [package]
  2. # ...
  3. links = "foo"
  4. build = "build.rs"

The documentation field (optional)

This field specifies a URL to a website hosting the crate's documentation.If no URL is specified in the manifest file, crates.io willautomatically link your crate to the corresponding docs.rs page.

Documentation links from specific hosts are blacklisted. Hosts are addedto the blacklist if they are known to not be hosting documentation and arepossibly of malicious intent e.g., ad tracking networks. URLs from thefollowing hosts are blacklisted:

  • rust-ci.orgDocumentation URLs from blacklisted hosts will not appear on crates.io, andmay be replaced by docs.rs links.

The exclude and include fields (optional)

You can explicitly specify that a set of file patterns should be ignored orincluded for the purposes of packaging. The patterns specified in theexclude field identify a set of files that are not included, and thepatterns in include specify files that are explicitly included.

The patterns should be gitignore-style patterns. Briefly:

  • foo matches any file or directory with the name foo anywhere in thepackage. This is equivalent to the pattern **/foo.
  • /foo matches any file or directory with the name foo only in the root ofthe package.
  • foo/ matches any directory with the name foo anywhere in the package.
  • Common glob patterns like *, ?, and [] are supported:
    • matches zero or more characters except /. For example, .htmlmatches any file or directory with the .html extension anywhere in thepackage.
    • ? matches any character except /. For example, foo? matches food,but not foo.
    • [] allows for matching a range of characters. For example, [ab]matches either a or b. [a-z] matches letters a through z.
  • / prefix matches in any directory. For example, /foo/bar matches thefile or directory bar anywhere that is directly under directory foo.
  • / suffix matches everything inside. For example, foo/ matches allfiles inside directory foo, including all files in subdirectories belowfoo.
  • // matches zero or more directories. For example, a//b matchesa/b, a/x/b, a/x/y/b, and so on.
  • ! prefix negates a pattern. For example, a pattern of src/**.rs and!foo.rs would match all files with the .rs extension inside the srcdirectory, except for any file named foo.rs.If git is being used for a package, the exclude field will be seeded withthe gitignore settings from the repository.
  1. [package]
  2. # ...
  3. exclude = ["build/**/*.o", "doc/**/*.html"]
  1. [package]
  2. # ...
  3. include = ["src/**/*", "Cargo.toml"]

The options are mutually exclusive: setting include will override anexclude. Note that include must be an exhaustive list of files as otherwisenecessary source files may not be included. The package's Cargo.toml isautomatically included.

The include/exclude list is also used for change tracking in some situations.For targets built with rustdoc, it is used to determine the list of files totrack to determine if the target should be rebuilt. If the package has abuild script that does not emit any rerun-if-* directives, then theinclude/exclude list is used for tracking if the build script should be re-runif any of those files change.

The publish field (optional)

The publish field can be used to prevent a package from being published to apackage registry (like crates.io) by mistake, for instance to keep a packageprivate in a company.

  1. [package]
  2. # ...
  3. publish = false

The value may also be an array of strings which are registry names that areallowed to be published to.

  1. [package]
  2. # ...
  3. publish = ["some-registry-name"]

The workspace field (optional)

The workspace field can be used to configure the workspace that this packagewill be a member of. If not specified this will be inferred as the firstCargo.toml with [workspace] upwards in the filesystem.

  1. [package]
  2. # ...
  3. workspace = "path/to/workspace/root"

For more information, see the documentation for the workspace table below.

Package metadata

There are a number of optional metadata fields also accepted under the[package] section:

  1. [package]
  2. # ...
  3. # A short blurb about the package. This is not rendered in any format when
  4. # uploaded to crates.io (aka this is not markdown).
  5. description = "..."
  6. # These URLs point to more information about the package. These are
  7. # intended to be webviews of the relevant data, not necessarily compatible
  8. # with VCS tools and the like.
  9. documentation = "..."
  10. homepage = "..."
  11. repository = "..."
  12. # This points to a file under the package root (relative to this `Cargo.toml`).
  13. # The contents of this file are stored and indexed in the registry.
  14. # crates.io will render this file and place the result on the crate's page.
  15. readme = "..."
  16. # This is a list of up to five keywords that describe this crate. Keywords
  17. # are searchable on crates.io, and you may choose any words that would
  18. # help someone find this crate.
  19. keywords = ["...", "..."]
  20. # This is a list of up to five categories where this crate would fit.
  21. # Categories are a fixed list available at crates.io/category_slugs, and
  22. # they must match exactly.
  23. categories = ["...", "..."]
  24. # This is an SPDX 2.1 license expression for this package. Currently
  25. # crates.io will validate the license provided against a whitelist of
  26. # known license and exception identifiers from the SPDX license list
  27. # 2.4. Parentheses are not currently supported.
  28. #
  29. # Multiple licenses can be separated with a `/`, although that usage
  30. # is deprecated. Instead, use a license expression with AND and OR
  31. # operators to get more explicit semantics.
  32. license = "..."
  33. # If a package is using a nonstandard license, then this key may be specified in
  34. # lieu of the above key and must point to a file relative to this manifest
  35. # (similar to the readme key).
  36. license-file = "..."
  37. # Optional specification of badges to be displayed on crates.io.
  38. #
  39. # - The badges pertaining to build status that are currently available are
  40. # Appveyor, CircleCI, Cirrus CI, GitLab, Azure DevOps and TravisCI.
  41. # - Available badges pertaining to code test coverage are Codecov and
  42. # Coveralls.
  43. # - There are also maintenance-related badges based on isitmaintained.com
  44. # which state the issue resolution time, percent of open issues, and future
  45. # maintenance intentions.
  46. #
  47. # If a `repository` key is required, this refers to a repository in
  48. # `user/repo` format.
  49. [badges]
  50. # Appveyor: `repository` is required. `branch` is optional; default is `master`
  51. # `service` is optional; valid values are `github` (default), `bitbucket`, and
  52. # `gitlab`; `id` is optional; you can specify the appveyor project id if you
  53. # want to use that instead. `project_name` is optional; use when the repository
  54. # name differs from the appveyor project name.
  55. appveyor = { repository = "...", branch = "master", service = "github" }
  56. # Circle CI: `repository` is required. `branch` is optional; default is `master`
  57. circle-ci = { repository = "...", branch = "master" }
  58. # Cirrus CI: `repository` is required. `branch` is optional; default is `master`
  59. cirrus-ci = { repository = "...", branch = "master" }
  60. # GitLab: `repository` is required. `branch` is optional; default is `master`
  61. gitlab = { repository = "...", branch = "master" }
  62. # Azure DevOps: `project` is required. `pipeline` is required. `build` is optional; default is `1`
  63. # Note: project = `organization/project`, pipeline = `name_of_pipeline`, build = `definitionId`
  64. azure-devops = { project = "...", pipeline = "...", build="2" }
  65. # Travis CI: `repository` in format "<user>/<project>" is required.
  66. # `branch` is optional; default is `master`
  67. travis-ci = { repository = "...", branch = "master" }
  68. # Codecov: `repository` is required. `branch` is optional; default is `master`
  69. # `service` is optional; valid values are `github` (default), `bitbucket`, and
  70. # `gitlab`.
  71. codecov = { repository = "...", branch = "master", service = "github" }
  72. # Coveralls: `repository` is required. `branch` is optional; default is `master`
  73. # `service` is optional; valid values are `github` (default) and `bitbucket`.
  74. coveralls = { repository = "...", branch = "master", service = "github" }
  75. # Is it maintained resolution time: `repository` is required.
  76. is-it-maintained-issue-resolution = { repository = "..." }
  77. # Is it maintained percentage of open issues: `repository` is required.
  78. is-it-maintained-open-issues = { repository = "..." }
  79. # Maintenance: `status` is required. Available options are:
  80. # - `actively-developed`: New features are being added and bugs are being fixed.
  81. # - `passively-maintained`: There are no plans for new features, but the maintainer intends to
  82. # respond to issues that get filed.
  83. # - `as-is`: The crate is feature complete, the maintainer does not intend to continue working on
  84. # it or providing support, but it works for the purposes it was designed for.
  85. # - `experimental`: The author wants to share it with the community but is not intending to meet
  86. # anyone's particular use case.
  87. # - `looking-for-maintainer`: The current maintainer would like to transfer the crate to someone
  88. # else.
  89. # - `deprecated`: The maintainer does not recommend using this crate (the description of the crate
  90. # can describe why, there could be a better solution available or there could be problems with
  91. # the crate that the author does not want to fix).
  92. # - `none`: Displays no badge on crates.io, since the maintainer has not chosen to specify
  93. # their intentions, potential crate users will need to investigate on their own.
  94. maintenance = { status = "..." }

The crates.io registry will render the description, displaythe license, link to the three URLs and categorize by the keywords. These keysprovide useful information to users of the registry and also influence thesearch ranking of a crate. It is highly discouraged to omit everything in apublished crate.

SPDX 2.1 license expressions are documentedhere. The current version of thelicense list is available here, and version 2.4is available here.

The metadata table (optional)

Cargo by default will warn about unused keys in Cargo.toml to assist indetecting typos and such. The package.metadata table, however, is completelyignored by Cargo and will not be warned about. This section can be used fortools which would like to store package configuration in Cargo.toml. Forexample:

  1. [package]
  2. name = "..."
  3. # ...
  4. # Metadata used when generating an Android APK, for example.
  5. [package.metadata.android]
  6. package-name = "my-awesome-android-app"
  7. assets = "path/to/static"

The default-run field

The default-run field in the [package] section of the manifest can be usedto specify a default binary picked by cargo run. For example, when there isboth src/bin/a.rs and src/bin/b.rs:

  1. [package]
  2. default-run = "a"

Dependency sections

See the specifying dependencies page forinformation on the [dependencies], [dev-dependencies],[build-dependencies], and target-specific [target.*.dependencies] sections.

The [profile.*] sections

Cargo supports custom configuration of how rustc is invoked through profiles atthe top level. Any manifest may declare a profile, but only the top levelpackage’s profiles are actually read. All dependencies’ profiles will beoverridden. This is done so the top-level package has control over how itsdependencies are compiled.

There are four currently supported profile names, all of which have the sameconfiguration available to them. Listed below is the configuration available,along with the defaults for each profile.

  1. # The development profile, used for `cargo build`.
  2. [profile.dev]
  3. opt-level = 0 # controls the `--opt-level` the compiler builds with.
  4. # 0-1 is good for debugging. 2 is well-optimized. Max is 3.
  5. # 's' attempts to reduce size, 'z' reduces size even more.
  6. debug = true # (u32 or bool) Include debug information (debug symbols).
  7. # Equivalent to `-C debuginfo=2` compiler flag.
  8. rpath = false # controls whether compiler should set loader paths.
  9. # If true, passes `-C rpath` flag to the compiler.
  10. lto = false # Link Time Optimization usually reduces size of binaries
  11. # and static libraries. Increases compilation time.
  12. # If true, passes `-C lto` flag to the compiler, and if a
  13. # string is specified like 'thin' then `-C lto=thin` will
  14. # be passed.
  15. debug-assertions = true # controls whether debug assertions are enabled
  16. # (e.g., debug_assert!() and arithmetic overflow checks)
  17. codegen-units = 16 # if > 1 enables parallel code generation which improves
  18. # compile times, but prevents some optimizations.
  19. # Passes `-C codegen-units`.
  20. panic = 'unwind' # panic strategy (`-C panic=...`), can also be 'abort'
  21. incremental = true # whether or not incremental compilation is enabled
  22. # This can be overridden globally with the CARGO_INCREMENTAL
  23. # environment variable or `build.incremental` config
  24. # variable. Incremental is only used for path sources.
  25. overflow-checks = true # use overflow checks for integer arithmetic.
  26. # Passes the `-C overflow-checks=...` flag to the compiler.
  27. # The release profile, used for `cargo build --release` (and the dependencies
  28. # for `cargo test --release`, including the local library or binary).
  29. [profile.release]
  30. opt-level = 3
  31. debug = false
  32. rpath = false
  33. lto = false
  34. debug-assertions = false
  35. codegen-units = 16
  36. panic = 'unwind'
  37. incremental = false
  38. overflow-checks = false
  39. # The testing profile, used for `cargo test` (for `cargo test --release` see
  40. # the `release` and `bench` profiles).
  41. [profile.test]
  42. opt-level = 0
  43. debug = 2
  44. rpath = false
  45. lto = false
  46. debug-assertions = true
  47. codegen-units = 16
  48. panic = 'unwind'
  49. incremental = true
  50. overflow-checks = true
  51. # The benchmarking profile, used for `cargo bench` (and the test targets and
  52. # unit tests for `cargo test --release`).
  53. [profile.bench]
  54. opt-level = 3
  55. debug = false
  56. rpath = false
  57. lto = false
  58. debug-assertions = false
  59. codegen-units = 16
  60. panic = 'unwind'
  61. incremental = false
  62. overflow-checks = false

The [features] section

Cargo supports features to allow expression of:

  • conditional compilation options (usable through cfg attributes);
  • optional dependencies, which enhance a package, but are not required; and
  • clusters of optional dependencies, such as postgres, that would include thepostgres package, the postgres-macros package, and possibly other packages(such as development-time mocking libraries, debugging tools, etc.).A feature of a package is either an optional dependency, or a set of otherfeatures. The format for specifying features is:
  1. [package]
  2. name = "awesome"
  3. [features]
  4. # The default set of optional packages. Most people will want to use these
  5. # packages, but they are strictly optional. Note that `session` is not a package
  6. # but rather another feature listed in this manifest.
  7. default = ["jquery", "uglifier", "session"]
  8. # A feature with no dependencies is used mainly for conditional compilation,
  9. # like `#[cfg(feature = "go-faster")]`.
  10. go-faster = []
  11. # The `secure-password` feature depends on the bcrypt package. This aliasing
  12. # will allow people to talk about the feature in a higher-level way and allow
  13. # this package to add more requirements to the feature in the future.
  14. secure-password = ["bcrypt"]
  15. # Features can be used to reexport features of other packages. The `session`
  16. # feature of package `awesome` will ensure that the `session` feature of the
  17. # package `cookie` is also enabled.
  18. session = ["cookie/session"]
  19. [dependencies]
  20. # These packages are mandatory and form the core of this package’s distribution.
  21. cookie = "1.2.0"
  22. oauth = "1.1.0"
  23. route-recognizer = "=2.1.0"
  24. # A list of all of the optional dependencies, some of which are included in the
  25. # above `features`. They can be opted into by apps.
  26. jquery = { version = "1.0.2", optional = true }
  27. uglifier = { version = "1.5.3", optional = true }
  28. bcrypt = { version = "*", optional = true }
  29. civet = { version = "*", optional = true }

To use the package awesome:

  1. [dependencies.awesome]
  2. version = "1.3.5"
  3. default-features = false # do not include the default features, and optionally
  4. # cherry-pick individual features
  5. features = ["secure-password", "civet"]

Rules

The usage of features is subject to a few rules:

  • Feature names must not conflict with other package names in the manifest. Thisis because they are opted into via features = […], which only has a singlenamespace.
  • With the exception of the default feature, all features are opt-in. To optout of the default feature, use default-features = false and cherry-pickindividual features.
  • Feature groups are not allowed to cyclically depend on one another.
  • Dev-dependencies cannot be optional.
  • Features groups can only reference optional dependencies.
  • When a feature is selected, Cargo will call rustc with —cfg feature="${feature_name}". If a feature group is included, it and all of itsindividual features will be included. This can be tested in code via#[cfg(feature = "foo")].Note that it is explicitly allowed for features to not actually activate anyoptional dependencies. This allows packages to internally enable/disablefeatures without requiring a new dependency.

Usage in end products

One major use-case for this feature is specifying optional features inend-products. For example, the Servo package may want to include optionalfeatures that people can enable or disable when they build it.

In that case, Servo will describe features in its Cargo.toml and they can beenabled using command-line flags:

  1. $ cargo build --release --features "shumway pdf"

Default features could be excluded using —no-default-features.

Usage in packages

In most cases, the concept of optional dependency in a library is bestexpressed as a separate package that the top-level application depends on.

However, high-level packages, like Iron or Piston, may want the ability tocurate a number of packages for easy installation. The current Cargo systemallows them to curate a number of mandatory dependencies into a single packagefor easy installation.

In some cases, packages may want to provide additional curation for optionaldependencies:

  • grouping a number of low-level optional dependencies together into a singlehigh-level feature;
  • specifying packages that are recommended (or suggested) to be included byusers of the package; and
  • including a feature (like secure-password in the motivating example) thatwill only work if an optional dependency is available, and would be difficultto implement as a separate package (for example, it may be overly difficult todesign an IO package to be completely decoupled from OpenSSL, with opt-in viathe inclusion of a separate package).In almost all cases, it is an antipattern to use these features outside ofhigh-level packages that are designed for curation. If a feature is optional, itcan almost certainly be expressed as a separate package.

The [workspace] section

Packages can define a workspace which is a set of crates that will all share thesame Cargo.lock and output directory. The [workspace] table can be definedas:

  1. [workspace]
  2. # Optional key, inferred from path dependencies if not present.
  3. # Additional non-path dependencies that should be included must be given here.
  4. # In particular, for a virtual manifest, all members have to be listed.
  5. members = ["path/to/member1", "path/to/member2", "path/to/member3/*"]
  6. # Optional key, empty if not present.
  7. exclude = ["path1", "path/to/dir2"]

Workspaces were added to Cargo as part of RFC 1525 and have a number ofproperties:

  • A workspace can contain multiple crates where one of them is the root crate.
  • The root crate's Cargo.toml contains the [workspace] table, but is notrequired to have other configuration.
  • Whenever any crate in the workspace is compiled, output is placed in theworkspace root (i.e., next to the root crate's Cargo.toml).
  • The lock file for all crates in the workspace resides in the workspace root.
  • The [patch], [replace] and [profile.*] sections in Cargo.tomlare only recognizedin the root crate's manifest, and ignored in member crates' manifests.The root crate of a workspace, indicated by the presence of [workspace] inits manifest, is responsible for defining the entire workspace. All pathdependencies residing in the workspace directory become members. You can addadditional packages to the workspace by listing them in the members key. Notethat members of the workspaces listed explicitly will also have their pathdependencies included in the workspace. Sometimes a package may have a lot ofworkspace members and it can be onerous to keep up to date. The members listcan also use globs to match multiple paths. Finally, the excludekey can be used to blacklist paths from being included in a workspace. This canbe useful if some path dependencies aren't desired to be in the workspace atall.

The package.workspace manifest key (described above) is used in member cratesto point at a workspace's root crate. If this key is omitted then it is inferredto be the first crate whose manifest contains [workspace] upwards in thefilesystem.

A crate may either specify package.workspace or specify [workspace]. Thatis, a crate cannot both be a root crate in a workspace (contain [workspace])and also be a member crate of another workspace (contain package.workspace).

Most of the time workspaces will not need to be dealt with as cargo new andcargo init will handle workspace configuration automatically.

Virtual Manifest

In workspace manifests, if the package table is present, the workspace rootcrate will be treated as a normal package, as well as a workspace. If thepackage table is not present in a workspace manifest, it is called a virtualmanifest.

Package selection

In a workspace, package-related cargo commands like cargo build apply topackages selected by -p / —package or —workspace command-line parameters.When neither is specified, the optional default-members configuration is used:

  1. [workspace]
  2. members = ["path/to/member1", "path/to/member2", "path/to/member3/*"]
  3. default-members = ["path/to/member2", "path/to/member3/foo"]

When specified, default-members must expand to a subset of members.

When default-members is not specified, the default is the root manifestif it is a package, or every member manifest (as if —workspace were specifiedon the command-line) for virtual workspaces.

The project layout

If your package is an executable, name the main source file src/main.rs. If itis a library, name the main source file src/lib.rs.

Cargo will also treat any files located in src/bin/*.rs as executables. If yourexecutable consists of more than just one source file, you might also use a directoryinside src/bin containing a main.rs file which will be treated as an executablewith a name of the parent directory.

Your package can optionally contain folders named examples, tests, andbenches, which Cargo will treat as containing examples,integration tests, and benchmarks respectively. Analogous to bin targets, theymay be composed of single files or directories with a main.rs file.

  1. src/ # directory containing source files
  2. lib.rs # the main entry point for libraries and packages
  3. main.rs # the main entry point for packages producing executables
  4. bin/ # (optional) directory containing additional executables
  5. *.rs
  6. */ # (optional) directories containing multi-file executables
  7. main.rs
  8. examples/ # (optional) examples
  9. *.rs
  10. */ # (optional) directories containing multi-file examples
  11. main.rs
  12. tests/ # (optional) integration tests
  13. *.rs
  14. */ # (optional) directories containing multi-file tests
  15. main.rs
  16. benches/ # (optional) benchmarks
  17. *.rs
  18. */ # (optional) directories containing multi-file benchmarks
  19. main.rs

To structure your code after you've created the files and folders for yourpackage, you should remember to use Rust's module system, which you can readabout in thebook.

See Configuring a target below for more details onmanually configuring target settings. See Targetauto-discovery below for more information oncontrolling how Cargo automatically infers targets.

Examples

Files located under examples are example uses of the functionality provided bythe library. When compiled, they are placed in the target/examples directory.

They can compile either as executables (with a main() function) or librariesand pull in the library by using extern crate <library-name>. They arecompiled when you run your tests to protect them from bitrotting.

You can run individual executable examples with the command cargo run —example <example-name>.

Specify crate-type to make an example be compiled as a library (additionalinformation about crate types is available inThe Rust Reference):

  1. [[example]]
  2. name = "foo"
  3. crate-type = ["staticlib"]

You can build individual library examples with the command cargo build —example <example-name>.

Tests

When you run cargo test, Cargo will:

  • compile and run your library’s unit tests, which are in the files reachablefrom lib.rs (naturally, any sections marked with #[cfg(test)] will beconsidered at this stage);
  • compile and run your library’s documentation tests, which are embedded insideof documentation blocks;
  • compile and run your library’s integration tests; and
  • compile your library’s examples.

Integration tests

Each file in tests/*.rs is an integration test. When you run cargo test,Cargo will compile each of these files as a separate crate. The crate can linkto your library by using extern crate <library-name>, like any other code thatdepends on it.

Cargo will not automatically compile files inside subdirectories of tests, butan integration test can import modules from these directories as usual. Forexample, if you want several integration tests to share some code, you can putthe shared code in tests/common/mod.rs and then put mod common; in each ofthe test files.

Configuring a target

All of the [[bin]], [lib], [[bench]], [[test]], and [[example]]sections support similar configuration for specifying how a target should bebuilt. The double-bracket sections like [[bin]] are array-of-table ofTOML, which means you canwrite more than one [[bin]] section to make several executables in your crate.

The example below uses [lib], but it also applies to all other sectionsas well. All values listed are the defaults for that option unless otherwisespecified.

  1. [package]
  2. # ...
  3. [lib]
  4. # The name of a target is the name of the library that will be generated. This
  5. # is defaulted to the name of the package, with any dashes replaced
  6. # with underscores. (Rust `extern crate` declarations reference this name;
  7. # therefore the value must be a valid Rust identifier to be usable.)
  8. name = "foo"
  9. # This field points at where the crate is located, relative to the `Cargo.toml`.
  10. path = "src/lib.rs"
  11. # A flag for enabling unit tests for this target. This is used by `cargo test`.
  12. test = true
  13. # A flag for enabling documentation tests for this target. This is only relevant
  14. # for libraries, it has no effect on other sections. This is used by
  15. # `cargo test`.
  16. doctest = true
  17. # A flag for enabling benchmarks for this target. This is used by `cargo bench`.
  18. bench = true
  19. # A flag for enabling documentation of this target. This is used by `cargo doc`.
  20. doc = true
  21. # If the target is meant to be a compiler plugin, this field must be set to true
  22. # for Cargo to correctly compile it and make it available for all dependencies.
  23. plugin = false
  24. # If the target is meant to be a "macros 1.1" procedural macro, this field must
  25. # be set to true.
  26. proc-macro = false
  27. # If set to false, `cargo test` will omit the `--test` flag to rustc, which
  28. # stops it from generating a test harness. This is useful when the binary being
  29. # built manages the test runner itself.
  30. harness = true
  31. # If set then a target can be configured to use a different edition than the
  32. # `[package]` is configured to use, perhaps only compiling a library with the
  33. # 2018 edition or only compiling one unit test with the 2015 edition. By default
  34. # all targets are compiled with the edition specified in `[package]`.
  35. edition = '2015'
  36. # Here's an example of a TOML "array of tables" section, in this case specifying
  37. # a binary target name and path.
  38. [[bin]]
  39. name = "my-cool-binary"
  40. path = "src/my-cool-binary.rs"

Target auto-discovery

By default, Cargo automatically determines the targets to build based on thelayout of the files on the filesystem. The targetconfiguration tables, such as [lib], [[bin]], [[test]], [[bench]], or[[example]], can be used to add additional targets that don't follow thestandard directory layout.

The automatic target discovery can be disabled so that only manuallyconfigured targets will be built. Setting the keys autobins, autoexamples,autotests, or autobenches to false in the [package] section willdisable auto-discovery of the corresponding target type.

Disabling automatic discovery should only be needed for specializedsituations. For example, if you have a library where you want a module namedbin, this would present a problem because Cargo would usually attempt tocompile anything in the bin directory as an executable. Here is a samplelayout of this scenario:

  1. ├── Cargo.toml
  2. └── src
  3. ├── lib.rs
  4. └── bin
  5. └── mod.rs

To prevent Cargo from inferring src/bin/mod.rs as an executable, setautobins = false in Cargo.toml to disable auto-discovery:

  1. [package]
  2. # …
  3. autobins = false

Note: For packages with the 2015 edition, the default for auto-discoveryis false if at least one target is manually defined in Cargo.toml.Beginning with the 2018 edition, the default is always true.

The required-features field (optional)

The required-features field specifies which features the target needs in orderto be built. If any of the required features are not selected, the target willbe skipped. This is only relevant for the [[bin]], [[bench]], [[test]],and [[example]] sections, it has no effect on [lib].

  1. [features]
  2. # ...
  3. postgres = []
  4. sqlite = []
  5. tools = []
  6. [[bin]]
  7. # ...
  8. required-features = ["postgres", "tools"]

Building dynamic or static libraries

If your package produces a library, you can specify which kind of library tobuild by explicitly listing the library in your Cargo.toml:

  1. # ...
  2. [lib]
  3. name = "..."
  4. crate-type = ["dylib"] # could be `staticlib` as well

The available options are dylib, rlib, staticlib, cdylib, andproc-macro.

You can read more about the different crate types in theRust Reference Manual

The [patch] Section

This section of Cargo.toml can be used to override dependencies withother copies. The syntax is similar to the [dependencies] section:

  1. [patch.crates-io]
  2. foo = { git = 'https://github.com/example/foo' }
  3. bar = { path = 'my/local/bar' }
  4. [dependencies.baz]
  5. git = 'https://github.com/example/baz'
  6. [patch.'https://github.com/example/baz']
  7. baz = { git = 'https://github.com/example/patched-baz', branch = 'my-branch' }

The [patch] table is made of dependency-like sub-tables. Each key after[patch] is a URL of the source that is being patched, or the name of aregistry. The name crates-io may be used to override the default registrycrates.io. The first [patch] in the example above demonstrates overridingcrates.io, and the second [patch] demonstrates overriding a git source.

Each entry in these tables is a normal dependency specification, the same asfound in the [dependencies] section of the manifest. The dependencies listedin the [patch] section are resolved and used to patch the source at theURL specified. The above manifest snippet patches the crates-io source (e.g.crates.io itself) with the foo crate and bar crate. It alsopatches the https://github.com/example/baz source with a my-branch thatcomes from elsewhere.

Sources can be patched with versions of crates that do not exist, and they canalso be patched with versions of crates that already exist. If a source ispatched with a crate version that already exists in the source, then thesource's original crate is replaced.

More information about overriding dependencies can be found in the overridingdependencies section of the documentation and RFC 1969 for thetechnical specification of this feature.

Using [patch] with multiple versions

You can patch in multiple versions of the same crate with the package key usedto rename dependencies. For example let's say that the serde crate has abugfix that we'd like to use to its 1.* series but we'd also like to prototypeusing a 2.0.0 version of serde we have in our git repository. To configure thiswe'd do:

  1. [patch.crates-io]
  2. serde = { git = 'https://github.com/serde-rs/serde' }
  3. serde2 = { git = 'https://github.com/example/serde', package = 'serde', branch = 'v2' }

The first serde = … directive indicates that serde 1.* should be used fromthe git repository (pulling in the bugfix we need) and the second serde2 = …directive indicates that the serde package should also be pulled from the v2branch of https://github.com/example/serde. We're assuming here thatCargo.toml on that branch mentions version 2.0.0.

Note that when using the package key the serde2 identifier here is actuallyignored. We simply need a unique name which doesn't conflict with other patchedcrates.

The [replace] Section

This section of Cargo.toml can be used to override dependencies withother copies. The syntax is similar to the [dependencies] section:

  1. [replace]
  2. "foo:0.1.0" = { git = 'https://github.com/example/foo' }
  3. "bar:1.0.2" = { path = 'my/local/bar' }

Each key in the [replace] table is a package IDspecification, which allows arbitrarily choosing a node in thedependency graph to override. The value of each key is the same as the[dependencies] syntax for specifying dependencies, except that you can'tspecify features. Note that when a crate is overridden the copy it's overriddenwith must have both the same name and version, but it can come from a differentsource (e.g., git or a local path).

More information about overriding dependencies can be found in the overridingdependencies section of the documentation.