2
votes

I have a hard time understanding the features entry in the Rust toml.

Let's say I have a dependency (in this case sqlx) saying

sqlx = { version = "0.4.0-beta.1", default-features = false, features = [ "runtime-tokio", "macros", "json", "mysql" ] }

The Rust book says regarding Features:

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-all, that would include the postgres 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 other features.

What does that mean in my case? Do I have to install, i.e. enter e.g. "runtime-tokio" as an additional dependency in my Cargo.toml or does sqlx already come with "runtime-tokio"?

BTW what are cfg-attributes?

1
Enabling a feature tells cargo to pull in all dependencies needed for the feature. You don't need to do anything else.Sven Marnach

1 Answers

4
votes

Whenever you specify features for a dependency, you're asking Cargo to compile that dependency differently, in a way that the crate has chosen to provide as an option. Often, but not always, the feature is named the same as a crate that it could depend on (to provide e.g. trait implementations).

Do I have to install, i.e. enter e.g. "runtime-tokio" as an additional dependency in my Cargo.toml or does sqlx already come with "runtime-tokio"?

No; the Cargo.toml for sqlx will take care of specifying needed dependencies for any combination of features.

what are cfg-attributes?

Attributes are the things written #[attribute_name_here], like #[test] and #[derive(Debug)]. The #[cfg(...)] attribute allows conditional compilation, i.e. telling the compiler to pretend certain parts of the source code don't exist.

Often, a feature has two effects:

  • It enables an optional dependency (this is specified in Cargo.toml, either explicitly in the [features] section or implicitly by the feature having the same name as a crate dependency).
  • It causes the code in the crate that uses that dependency to be compiled (rather than ignored), using conditional compilation.