|
2 | 2 |
|
3 | 3 | 🚧 The 2024 Edition has not yet been released and hence this section is still "under construction".
|
4 | 4 |
|
5 |
| -This feature has not yet been implemented. |
6 |
| -More information may be found in the tracking issue at <https://github.com/rust-lang/cargo/issues/12826>. |
7 |
| - |
8 | 5 | ## Summary
|
9 | 6 |
|
| 7 | +- Optional dependencies must now be explicitly specified in the `[features]` table. |
| 8 | + |
10 | 9 | ## Details
|
11 | 10 |
|
| 11 | +In previous editions, when an [optional dependency] is specified, Cargo would automatically add an implicit [feature] of the same name as the dependency. For example: |
| 12 | + |
| 13 | +```toml |
| 14 | +[dependencies] |
| 15 | +jpeg-decoder = { version = "0.3.1", optional = true } |
| 16 | +``` |
| 17 | + |
| 18 | +This would automatically add a feature `jpeg-decoder = ["dep:jpeg-decoder"]` to provide a way to enable the dependency. |
| 19 | +The `dep:` entries are specific syntax for referring to optional dependencies. |
| 20 | +This implicit feature is only added if `"dep:jpeg-decoder"` is not specified in any other feature. |
| 21 | + |
| 22 | +In the 2024 Edition, this implicit feature is no longer added, and you are required to explicitly specify the dependency in the `[features]` table. |
| 23 | +For example, instead of exposing the particular internal name of some dependency, you may consider using a more general term for the feature name: |
| 24 | + |
| 25 | +```toml |
| 26 | +[features] |
| 27 | +graphics = ["dep:jpeg-decoder"] |
| 28 | +``` |
| 29 | + |
| 30 | +`cargo add --optional <NAME>` automatically adds a feature for the dependency to the `[features]` table if it isn't already there. |
| 31 | + |
| 32 | +### Motivation |
| 33 | + |
| 34 | +One reason for requiring this to be explicit is that it encourages a conscious decision about the public exposure of the feature name, and makes it clearer when reading the `[features]` table which features exist. |
| 35 | +This can help avoid tying the implementation details (the dependency names) to the public set of feature names. |
| 36 | + |
| 37 | +Also, removing features is a [SemVer incompatible change][semver], which may not be obvious when removing an optional dependency that you thought was private. |
| 38 | + |
12 | 39 | ## Migration
|
| 40 | + |
| 41 | +When using `cargo fix --edition`, Cargo will automatically update your `Cargo.toml` file to include the implicit features if necessary. |
| 42 | + |
| 43 | +If you would prefer to update your `Cargo.toml` manually, add a `foo = ["dep:foo"]` entry for each optional dependency named *foo* if `dep:foo` is not already specified anywhere in the `[features]` table. |
| 44 | + |
| 45 | +[optional dependency]: ../../cargo/reference/features.html#optional-dependencies |
| 46 | +[feature]: ../../cargo/reference/features.html |
| 47 | +[semver]: ../../cargo/reference/semver.html#cargo-feature-remove |
0 commit comments