url stringlengths 11 2.25k | text stringlengths 88 50k | ts timestamp[s]date 2026-01-13 08:47:33 2026-01-13 09:30:40 |
|---|---|---|
https://doc.rust-lang.org/std/process/trait.Termination.html#required-methods | Termination in std::process - Rust This old browser is unsupported and will most likely display funky things. Termination std 1.92.0 (ded5c06cf 2025-12-08) Termination Required Methods report Implementors In std:: process std :: process Trait Termination Copy item path 1.61.0 · Source pub trait Termination { // Required method fn report (self) -> ExitCode ; } Expand description A trait for implementing arbitrary return types in the main function. The C-main function only supports returning integers. So, every type implementing the Termination trait has to be converted to an integer. The default implementations are returning libc::EXIT_SUCCESS to indicate a successful execution. In case of a failure, libc::EXIT_FAILURE is returned. Because different runtimes have different specifications on the return value of the main function, this trait is likely to be available only on standard library’s runtime for convenience. Other runtimes are not required to provide similar functionality. Required Methods § 1.61.0 · Source fn report (self) -> ExitCode Is called to get the representation of the value as status code. This status code is returned to the operating system. Implementors § 1.61.0 · Source § impl Termination for Infallible 1.61.0 · Source § impl Termination for ! 1.61.0 · Source § impl Termination for () 1.61.0 · Source § impl Termination for ExitCode 1.61.0 · Source § impl<T: Termination , E: Debug > Termination for Result <T, E> | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#railroad-Attr | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---keep-going | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/std/process/trait.Termination.html#implementors | Termination in std::process - Rust This old browser is unsupported and will most likely display funky things. Termination std 1.92.0 (ded5c06cf 2025-12-08) Termination Required Methods report Implementors In std:: process std :: process Trait Termination Copy item path 1.61.0 · Source pub trait Termination { // Required method fn report (self) -> ExitCode ; } Expand description A trait for implementing arbitrary return types in the main function. The C-main function only supports returning integers. So, every type implementing the Termination trait has to be converted to an integer. The default implementations are returning libc::EXIT_SUCCESS to indicate a successful execution. In case of a failure, libc::EXIT_FAILURE is returned. Because different runtimes have different specifications on the return value of the main function, this trait is likely to be available only on standard library’s runtime for convenience. Other runtimes are not required to provide similar functionality. Required Methods § 1.61.0 · Source fn report (self) -> ExitCode Is called to get the representation of the value as status code. This status code is returned to the operating system. Implementors § 1.61.0 · Source § impl Termination for Infallible 1.61.0 · Source § impl Termination for ! 1.61.0 · Source § impl Termination for () 1.61.0 · Source § impl Termination for ExitCode 1.61.0 · Source § impl<T: Termination , E: Debug > Termination for Result <T, E> | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package--q | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/edition-guide/editions/index.html#edition-migration-is-easy-and-largely-automated | What are editions? - The Rust Edition Guide Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Edition Guide What are Editions? In May 2015, the release of Rust 1.0 established " stability without stagnation " as a core Rust axiom. Since then, Rust has committed to a pivotal rule: once a feature is released through stable , contributors will continue to support that feature for all future releases. However, there are times when it's useful to make backwards-incompatible changes to the language. A common example is the introduction of a new keyword. For instance, early versions of Rust didn't feature the async and await keywords. If Rust had suddenly introduced these new keywords, some code would have broken: let async = 1; would no longer work. Rust uses editions to solve this problem. When there are backwards-incompatible changes, they are pushed into the next edition. Since editions are opt-in, existing crates won't use the changes unless they explicitly migrate into the new edition. For example, the latest version of Rust doesn't treat async as a keyword unless edition 2018 or later is chosen. Each crate chooses its edition within its Cargo.toml file . When creating a new crate with Cargo, it will automatically select the newest stable edition. Editions do not split the ecosystem When creating editions, there is one most consequential rule: crates in one edition must seamlessly interoperate with those compiled with other editions. In other words, each crate can decide when to migrate to a new edition independently. This decision is 'private' - it won't affect other crates in the ecosystem. For Rust, this required compatibility implies some limits on the kinds of changes that can be featured in an edition. As a result, changes found in new Rust editions tend to be 'skin deep'. All Rust code - regardless of edition - will ultimately compile down to the same internal representation within the compiler. Edition migration is easy and largely automated Rust aims to make upgrading to a new edition an easy process. When a new edition releases, crate authors may use automatic migration tooling within cargo to migrate. Cargo will then make minor changes to the code to make it compatible with the new version. For example, when migrating to Rust 2018, anything named async will now use the equivalent raw identifier syntax : r#async . Cargo's automatic migrations aren't perfect: there may still be corner cases where manual changes are required. It aims to avoid changes to semantics that could affect the correctness or performance of the code. What this guide covers In addition to tooling, this Rust Edition Guide also covers the changes that are part of each edition. It describes each change and links to additional details, if available. It also covers corner cases or tricky details crate authors should be aware of. Crate authors should find: An overview of editions A migration guide for specific editions A quick troubleshooting reference when automated tooling isn't working. | 2026-01-13T09:29:13 |
https://aws.amazon.com/blogs/big-data/automate-and-orchestrate-amazon-emr-jobs-using-aws-step-functions-and-amazon-eventbridge/ | Automate and orchestrate Amazon EMR jobs using AWS Step Functions and Amazon EventBridge | AWS Big Data Blog Skip to Main Content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Blogs Home Blogs Editions AWS Big Data Blog Automate and orchestrate Amazon EMR jobs using AWS Step Functions and Amazon EventBridge by Senthil Kamala Rathinam and Shashidhar Makkapati on 15 SEP 2025 in Advanced (300) , Amazon CloudWatch , Amazon EC2 , Amazon EMR , Amazon EventBridge , Analytics , AWS Step Functions , Technical How-to Permalink Comments Share Many enterprises are adopting Apache Spark for scalable data processing tasks such as extract, transform, and load (ETL), batch analytics, and data enrichment. As data pipelines evolve, the need for flexible and cost-efficient execution environments that support automation, governance, and performance at scale also evolve in parallel. Amazon EMR provides a powerful environment to run Spark workloads, and depending on workload characteristics and compliance requirements, teams can choose between fully managed options like Amazon EMR Serverless or more customizable configurations using Amazon EMR on Amazon Elastic Compute Cloud (Amazon EC2) . In use cases where infrastructure control, data locality, or strict security postures are essential, such as in financial services, healthcare, or government, running transient EMR on EC2 clusters becomes a preferred choice. However, orchestrating the full lifecycle of these clusters, from provisioning to job submission and eventual teardown, can introduce operational overhead and risk if done manually. To streamline this process, the AWS Cloud offers built-in orchestration capabilities using AWS Step Functions and Amazon EventBridge . Together, these services help you automate and schedule the entire EMR job lifecycle, reducing manual intervention while optimizing cost and compliance. Step Functions provides the workflow logic to manage cluster creation, Spark job execution, and cluster termination, and EventBridge schedules these workflows based on business or operational needs. In this post, we discuss how to build a fully automated, scheduled Spark processing pipeline using Amazon EMR on EC2, orchestrated with Step Functions and triggered by EventBridge. We walk through how to deploy this solution using AWS CloudFormation , processes COVID-19 public dataset data in Amazon Simple Storage Service (Amazon S3) , and store the aggregated results in Amazon S3. This architecture is ideal for periodic or scheduled batch processing scenarios where infrastructure control, auditability, and cost-efficiency are critical. Solution overview This solution uses the publicly available COVID-19 dataset to illustrate how to build a modular, scheduled architecture for scalable and cost-efficient batch processing for time-bound data workloads.The solution follows these steps: Raw COVID-19 data in CSV format is stored in an S3 input bucket. A scheduled rule in EventBridge triggers a Step Functions workflow. The Step Functions workflow provisions a transient Amazon EMR cluster using EC2 instances. A PySpark job is submitted to the cluster to calculate COVID-19 hospital utilization data to compute monthly state-level averages of inpatient and ICU bed utilization, and COVID-19 patient percentages. The processed results are written back to an S3 output bucket. After successful job completion, the EMR cluster is automatically deleted. Logs are persisted to Amazon S3 for observability and troubleshooting. By automating this workflow, you alleviate the need to manually manage EMR clusters while gaining cost-efficiency by running compute only when needed. This architecture is ideal for periodic Spark jobs such as ETL pipelines, regulatory reporting, and batch analytics, especially when control, compliance, and customization are required.The following diagram illustrates the architecture for this use case. The infrastructure is deployed using AWS CloudFormation to provide consistency and repeatability. AWS Identity and Access Management (IAM) roles grant least‑privilege access to Step Functions, Amazon EMR, EC2 instances, and S3 buckets, and optional AWS Key Management Service (AWS KMS) encryption can secure data at rest in Amazon S3 and Amazon CloudWatch Logs . By combining a scheduled trigger, stateful orchestration, and centralized logging, this solution delivers a fully automated, cost‑optimized, and secure way to run transient Spark workloads in production. Prerequisites Before you get started, make sure you have the following prerequisites: An AWS account. If you don’t have one, you can sign up for one. An IAM user with administrator access. For instructions, see Create a user with administrative access . The AWS Command Line Interface (AWS CLI) is installed on your local machine A default virtual private cloud (VPC) and subnet in the target AWS Region where you plan to run the CloudFormation template. Set up resources with AWS CloudFormation To provision the required resources using a single CloudFormation template, complete the following steps: Sign in to the AWS Management Console as an admin user. Clone the sample repository to your local machine or AWS CloudShell and navigate into the project directory. git clone https://github.com/aws-samples/sample-emr-transient-cluster-step-functions-eventbridge.git cd sample-emr-transient-cluster-step-functions-eventbridge Set an environment variable for the AWS Region where you plan to deploy the resources. Replace the placeholder with your Region code, for example, us-east-1 . export AWS_REGION=<YOUR AWS REGION> Deploy the stack using the following command. Update the stack name if needed. In this example, the stack is created with the name covid19-analysis . aws cloudformation deploy \ --template-file emr_transient_cluster_step_functions_eventbridge.yaml \ --stack-name covid19-analysis \ --capabilities CAPABILITY_IAM \ --region $AWS_REGION You can monitor the stack creation progress on the AWS CloudFormation console on the Events tab. The deployment typically completes in under 5 minutes. After the stack is successfully created, go to the Outputs tab on the AWS CloudFormation console and note the following values for use in later steps: InputBucketName OutputBucketName LogBucketName Set up the COVID-19 dataset With your infrastructure in place, complete the following steps to set up the input data: Download the COVID-19 data CSV file from HealthData.gov to your local machine. Rename the downloaded file to covid19-dataset.csv. Upload the renamed file to your S3 input bucket under the raw/ folder path. Set up the PySpark Script Complete the following steps to set up the PySpark script: Open AWS CloudShell from the console. Confirm that you are working inside the sample-emr-transient-cluster-step-functions-eventbridge directory before running the next command. Copy the PySpark script needed for this walkthrough into your input bucket: aws s3 cp covid19_processor.py s3://<InputBucketName>/scripts/ This script processes COVID-19 hospital utilization data stored as CSV files in your S3 input bucket. When running the job, provide the following command-line arguments: --input – The S3 path to the input CSV files --output – The S3 path to store the processed results The script reads the raw dataset, standardizes various date formats, and filters out records with invalid or missing dates. It then extracts key utilization metrics such as inpatient bed usage, ICU bed usage, and the percentage of beds occupied by COVID-19 patients and calculates monthly averages grouped by state. The aggregated output is saved as timestamped CSV files in the specified S3 location. This example demonstrates how you can use PySpark to efficiently clean, transform, and analyze large-scale healthcare data to gain actionable insights on hospital capacity trends during the pandemic. Configure a schedule in EventBridge The Step Functions state machine is by default scheduled to run on December 31, 2025, as a one-time execution. You can update the schedule for recurring or one-time execution as needed. Complete the following steps: On the EventBridge console, choose Schedules under Scheduler in the navigation pane. Select the schedule named <StackName>-covid19-analysis and choose Edit . Set your preferred schedule pattern. If you want to run the schedule one time, select One-time schedule for Occurrence and enter a date and time. If you want to run this on a recurring basis, select Recurring schedule . Specify the schedule type as either Cron-based schedule or Rate-based schedule as needed. Choose Next twice and choose Save schedule . Start the workflow in Step Functions Based on your EventBridge schedule, the Step Functions workflow will run automatically. For this walkthrough, complete the following steps to trigger it manually: On the Step Functions console, choose State machines in the navigation pane. Choose the state machine that begins with Covid19AnalysisStateMachine-*. Choose Start execution . In the Input section, provide the following JSON (provide the log bucket and output bucket names with the appropriate values captured earlier): { "LogUri": "s3://<LogBucketName>/logs/", "OutputS3Location": "s3://<OutputBucketName>/processed/" } Choose Start execution to initiate the workflow. Monitor the EMR job and workflow execution After you start the workflow, you can track both the Step Functions state transitions and the EMR job progress in real time on the console. Monitor the Step Functions state machine Complete the following steps to monitor the Step Functions state machine: On the Step Functions console, choose State machines in the navigation pane. Choose the state machine that begins with Covid19AnalysisStateMachine-*. Choose the running execution to view the visual workflow. Each state node will update as it progresses—green for success, red for failure. To explore a step, choose its node and inspect the input, output, and error details in the side pane. The following screenshot shows an example of a successfully executed workflow. Monitor the EMR cluster and EMR step Complete the following steps to monitor the EMR cluster and EMR step status: While the cluster is active, open the Amazon EMR console and choose Clusters in the navigation pane. Locate the Covid19Cluster transient EMR cluster. Initially, it will be in Starting status. On the Steps tab, you can see your Spark submit step listed. As the job progresses, the step status changes from Pending to Running to finally Completed or Failed . Choose the Applications tab to view the application UIs, in which you can access the Spark History Server and YARN Timeline Server for monitoring and troubleshooting. Monitor CloudWatch logs To enable CloudWatch logging and enhanced monitoring for your EMR on EC2 cluster, refer to Amazon EMR on EC2 – Enhanced Monitoring with CloudWatch using custom metrics and logs . This guide explains how to install and configure the CloudWatch agent using a bootstrap action, so you can stream system-level metrics (such as CPU, memory, and disk usage) and application logs from EMR nodes directly to CloudWatch. With this setup, you can gain real-time visibility into cluster health and performance, simplify troubleshooting, and retain critical logs even after the cluster is terminated. For this walkthrough, check the logs in the S3 log output location. Confirm cluster deletion When the Spark step is complete, Step Functions will automatically delete the Amazon EMR cluster. Refresh the Clusters page on the Amazon EMR console. You should see your cluster status change from Terminating to Terminated within a minute. By following these steps, you gain full end-to-end visibility into your workflow from the moment the Step Functions state machine is triggered to the automatic shutdown of the EMR cluster. You can monitor execution progress, troubleshoot issues, confirm job success, and continuously optimize your transient Spark workloads. Verify job output in Amazon S3 When the job is complete, complete the following steps to check the processed results in the S3 output bucket: On the Amazon S3 console, choose Buckets in the navigation pane. Open the output S3 bucket you noted earlier. Open the processed folder. Navigate into the timestamped subfolder to view the CSV output file. Download the CSV file to view the processed results, as shown in the following screenshot. Monitoring and troubleshooting To monitor the progress of your Spark job running on a transient EMR on EC2 cluster, use the Step Functions console. It provides real-time visibility into each state transition in your workflow, from cluster creation and job submission to cluster deletion. This makes it straightforward to track execution flow and identify where issues might occur.During job execution, you can use the Amazon EMR console to access cluster-level monitoring. This includes YARN application statuses, step-level logs, and overall cluster health. If CloudWatch logging is enabled in your job configuration, driver and executor logs stream in near real time, so you can quickly detect and diagnose errors, resource constraints, or data skew within your Spark application. After the workflow is complete, regardless of whether it succeeds or fails, you can perform a detailed post-execution analysis by reviewing the logs stored in the S3 bucket specified in the LogUri parameter. This log directory includes standard output and error logs, along with Spark history files, offering insights into execution behavior and performance metrics. For continued access to the Spark UI during job execution, you can use persistent application UIs on the EMR console. These links remain accessible even after the cluster is stopped, enabling deeper root-cause analysis and performance tuning for future runs. This visibility into both workflow orchestration and job execution can help teams optimize their Spark workloads, reduce troubleshooting time, and build confidence in their EMR automation pipelines. Clean up To avoid incurring ongoing charges, clean up the resources provisioned during this walkthrough: Empty the S3 buckets: On the Amazon S3 console, choose Buckets in the navigation pane. Select the input, output, and log buckets used in this tutorial. Choose Empty to remove all objects before deleting the buckets (optional). Delete the CloudFormation stack: On the AWS CloudFormation console, choose Stacks in the navigation pane. Select the stack you created for this solution and choose Delete . Confirm the deletion to remove associated resources. Conclusion In this post, we showed how to build a fully automated and cost-effective Spark processing pipeline using Step Functions, EventBridge, and Amazon EMR on EC2. The workflow provisions a transient EMR cluster, runs a Spark job to process data, and stops the cluster after the job completes. This approach helps reduce costs while giving you full control over the process. This solution is ideal for scheduled data processing tasks such as ETL jobs, log analytics, or batch reporting, especially when you need detailed control over infrastructure, security, and compliance settings. To get started, deploy the solution in your environment using the CloudFormation stack provided and adjust it to fit your data processing needs. Check out the Step Functions Developer Guide and Amazon EMR Management Guide to explore further. Share your feedback and ideas in the comments or connect with your AWS Solutions Architect to fine-tune this pattern for your use case. About the authors Senthil Kamala Rathinam Senthil is a Solutions Architect at Amazon Web Services, specializing in Data and Analytics for banking customers across North America. With deep expertise in Data and Analytics, AI/ML, and Generative AI, he helps organizations unlock business value through data-driven transformation. Beyond work, Senthil enjoys spending time with his family and playing badminton. Shashi Makkapati Shashi is a Senior Solutions Architect serving banking customers across North America. He specializes in data analytics, AI/ML, and generative AI, focusing on innovative solutions that transform financial organizations. Shashi is passionate about leveraging technology to solve complex business challenges in the banking sector. Outside of work, he enjoys traveling and spending quality time with his family. Loading comments… Resources Amazon Athena Amazon EMR Amazon Kinesis Amazon MSK Amazon QuickSight Amazon Redshift AWS Glue Follow Twitter Facebook LinkedIn Twitch Email Updates @charset "UTF-8";[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4{position:relative;transition:box-shadow .3s ease}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_5962fadc:hover{box-shadow:var(--rg-shadow-gray-elevation-1, 1px 1px 20px rgba(0, 0, 0, .1))}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0.rgft_e79955da,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003.rgft_e79955da,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_5962fadc:hover.rgft_e79955da{box-shadow:var(--rg-shadow-gray-elevation-2, 1px 1px 24px rgba(0, 0, 0, .25))}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003:hover{box-shadow:none}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde{position:relative;transform-style:preserve-3d;overflow:unset!important}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:before{content:"";position:absolute;inset:0;border-radius:inherit;transform:translateZ(-1px);pointer-events:none;transition-property:filter,inset;transition-duration:.3s;transition-timing-function:ease;background-clip:content-box!important;padding:1px}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0:before{filter:blur(15px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0.rgft_4df65418:hover:before{filter:blur(20px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_5962fadc:hover:before{filter:blur(15px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003:before{filter:blur(15px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003:hover:before{filter:none}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_e90ac70d:active:before{filter:blur(8px)!important}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_a4f580d2:before{filter:blur(8px)!important}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=fuchsia] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=fuchsia].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-fuchsia, linear-gradient(123deg, #fa6f00 0%, #e433ff 50%, #8575ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=fuchsia] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=fuchsia].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-fuchsia, linear-gradient(123deg, #d14600 0%, #c300e0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=indigo] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=indigo].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-indigo, linear-gradient(123deg, #0099ff 0%, #5c7fff 50%, #8575ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=indigo] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=indigo].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-indigo, linear-gradient(123deg, #006ce0 0%, #295eff 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=orange] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=orange].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-orange, linear-gradient(123deg, #ff1ae0 0%, #ff386a 50%, #fa6f00 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=orange] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=orange].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-orange, linear-gradient(123deg, #d600ba 0%, #eb003b 50%, #d14600 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=teal] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=teal].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-teal, linear-gradient(123deg, #00bd6b 0%, #00a4bd 50%, #0099ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=teal] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=teal].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-teal, linear-gradient(123deg, #008559 0%, #007e94 50%, #006ce0 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=blue] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=blue].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-blue, linear-gradient(123deg, #00bd6b 0%, #0099ff 50%, #8575ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=blue] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=blue].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-blue, linear-gradient(123deg, #008559 0%, #006ce0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=violet] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=violet].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-violet, linear-gradient(123deg, #ad5cff 0%, #0099ff 50%, #00a4bd 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=violet] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=violet].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-violet, linear-gradient(123deg, #962eff 0%, #006ce0 50%, #007e94 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=purple] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=purple].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-purple, linear-gradient(123deg, #ff1ae0 0%, #8575ff 50%, #00a4bd 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=purple] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=purple].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-purple, linear-gradient(123deg, #d600ba 0%, #6842ff 50%, #007e94 100%))}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:linear-gradient(123deg,#d14600,#c300e0,#6842ff)}[data-eb-6a8f3296] [data-rg-theme=fuchsia] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=fuchsia].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-fuchsia, linear-gradient(123deg, #d14600 0%, #c300e0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-theme=indigo] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=indigo].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-indigo, linear-gradient(123deg, #006ce0 0%, #295eff 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-theme=orange] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=orange].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-orange, linear-gradient(123deg, #d600ba 0%, #eb003b 50%, #d14600 100%))}[data-eb-6a8f3296] [data-rg-theme=teal] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=teal].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-teal, linear-gradient(123deg, #008559 0%, #007e94 50%, #006ce0 100%))}[data-eb-6a8f3296] [data-rg-theme=blue] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=blue].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-blue, linear-gradient(123deg, #008559 0%, #006ce0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-theme=violet] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=violet].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-violet, linear-gradient(123deg, #962eff 0%, #006ce0 50%, #007e94 100%))}[data-eb-6a8f3296] [data-rg-theme=purple] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=purple].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-purple, linear-gradient(123deg, #d600ba 0%, #6842ff 50%, #007e94 100%))}[data-eb-6a8f3296] a.rgft_f7822e54,[data-eb-6a8f3296] button.rgft_f7822e54{--button-size: 44px;--button-pad-h: 24px;--button-pad-borderless-h: 26px;border:2px solid var(--rg-color-background-page-inverted, #0F141A);padding:8px var(--button-pad-h, 24px);border-radius:40px!important;align-items:center;justify-content:center;display:inline-flex;height:var(--button-size, 44px);text-decoration:none!important;text-wrap:nowrap;cursor:pointer;position:relative;transition:all .3s ease}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_094d67e1,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_094d67e1{--button-size: 32px;--button-pad-h: 14px;--button-pad-borderless-h: 16px}[data-eb-6a8f3296] a.rgft_f7822e54>span,[data-eb-6a8f3296] button.rgft_f7822e54>span{color:var(--btn-text-color, inherit)!important}[data-eb-6a8f3296] a.rgft_f7822e54:focus-visible,[data-eb-6a8f3296] button.rgft_f7822e54:focus-visible{outline:2px solid var(--rg-color-focus-ring, #006CE0)!important;outline-offset:4px!important;transition:outline 0s}[data-eb-6a8f3296] a.rgft_f7822e54:focus:not(:focus-visible),[data-eb-6a8f3296] button.rgft_f7822e54:focus:not(:focus-visible){outline:none!important}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_303c672b,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_303c672b{--btn-text-color: var(--rg-color-text-utility-inverted, #FFFFFF);background-color:var(--rg-color-btn-primary-bg, #161D26);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_18409398,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_18409398{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-bg, #FFFFFF);border-color:var(--rg-color-background-page-inverted, #0F141A)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_090951dc{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-background-object, #F3F3F7);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_15529d9f,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_15529d9f{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-bg, #FFFFFF);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb950a4e{--btn-text-color: var(--rg-color-text-utility, #161D26);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb950a4e{background-image:linear-gradient(97deg,#ffc0ad,#f8c7ff 37.79%,#d2ccff 75.81%,#c2d1ff)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb950a4e{--rg-gradient-angle:97deg;background-image:var(--rg-gradient-a, linear-gradient(120deg, #f8c7ff 20.08%, #d2ccff 75.81%))}[data-eb-6a8f3296] [data-rg-mode=dark] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] [data-rg-mode=dark] button.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] a[data-rg-mode=dark].rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button[data-rg-mode=dark].rgft_f7822e54.rgft_bb950a4e{background-image:var(--rg-gradient-a, linear-gradient(120deg, #78008a 24.25%, #b2008f 69.56%))}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb419678,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb419678{--btn-text-color: var(--rg-color-text-utility-inverted, #FFFFFF);background-color:var(--rg-color-btn-visited-bg, #656871);border-color:var(--rg-color-btn-visited-bg, #656871)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb419678.rgft_18409398,[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb419678.rgft_15529d9f,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb419678.rgft_18409398,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb419678.rgft_15529d9f{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-visited-bg, #FFFFFF)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5{--btn-text-color: var(--rg-color-btn-disabled-text, #B4B4BB);background-color:var(--rg-color-btn-disabled-bg, #F3F3F7);border-color:var(--rg-color-btn-disabled-bg, #F3F3F7);cursor:default}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5.rgft_18409398,[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5.rgft_15529d9f,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5.rgft_18409398,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5.rgft_15529d9f{border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5.rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5.rgft_090951dc{--btn-text-color: var(--rg-color-btn-tertiary-disabled-text, #B4B4BB);background-color:#0000}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_18409398:not(.rgft_bb950a4e),[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_15529d9f:not(.rgft_bb950a4e),[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_18409398:not(.rgft_bb950a4e),[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_15529d9f:not(.rgft_bb950a4e){--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-bg, #FFFFFF)}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc{box-shadow:none}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc{background-image:linear-gradient(97deg,#ffc0ad80,#f8c7ff80 37.79%,#d2ccff80 75.81%,#c2d1ff80)}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc{--rg-gradient-angle:97deg;background-image:var(--rg-gradient-a-50, linear-gradient(120deg, #f8c7ff 20.08%, #d2ccff 75.81%))}[data-eb-6a8f3296] [data-rg-mode=dark] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] [data-rg-mode=dark] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] a[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:hover:not(.rgft_badebaf5),[data-eb-6a8f3296] button[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:hover:not(.rgft_badebaf5){background-image:var(--rg-gradient-a-50, linear-gradient(120deg, #78008a 24.25%, #b2008f 69.56%))}[data-eb-6a8f3296] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc{box-shadow:none}[data-eb-6a8f3296] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc{background-image:linear-gradient(97deg,#ffc0ad,#f8c7ff 37.79%,#d2ccff 75.81%,#c2d1ff)}[data-eb-6a8f3296] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc{--rg-gradient-angle:97deg;background-image:var(--rg-gradient-a-pressed, linear-gradient(120deg, rgba(248, 199, 255, .5) 20.08%, #d2ccff 75.81%))}[data-eb-6a8f3296] [data-rg-mode=dark] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] [data-rg-mode=dark] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] a[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:active:not(.rgft_badebaf5),[data-eb-6a8f3296] button[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:active:not(.rgft_badebaf5){background-image:var(--rg-gradient-a-pressed, linear-gradient(120deg, rgba(120, 0, 138, .5) 24.25%, #b2008f 69.56%))}[data-eb-6a8f3296] .rgft_8711ccd9{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:#0000;border:none;margin:0}[data-eb-6a8f3296] .rgft_8711ccd9.rgft_5e58a6df{text-align:center}[data-eb-6a8f3296] .rgft_8711ccd9.rgft_b7ada98b{display:block}[data-eb-6a8f3296] .rgft_8711ccd9.rgft_beb26dc7{font-family:Amazon Ember Mono,Consolas,Andale Mono WT,Andale Mono,Lucida Console,Lucida Sans Typewriter,DejaVu Sans Mono,Bitstream Vera Sans Mono,Liberation Mono,Nimbus Mono L,Monaco,Courier New,Courier,monospace}[data-eb-6a8f3296] .rgft_8711ccd9 a{display:inline;position:relative;cursor:pointer;text-decoration:none!important;color:var(--rg-color-link-default, #006CE0);background:linear-gradient(to right,currentcolor,currentcolor);background-size:100% .1em;background-position:0 100%;background-repeat:no-repeat}[data-eb-6a8f3296] .rgft_8711ccd9 a:focus-visible{color:var(--rg-color-link-focus, #006CE0)}[data-eb-6a8f3296] .rgft_8711ccd9 a:hover{color:var(--rg-color-link-hover, #003B8F);animation:rgft_d72bdead .3s cubic-bezier(0,0,.2,1)}[data-eb-6a8f3296] .rgft_8711ccd9 a:visited{color:var(--rg-color-link-visited, #6842FF)}@keyframes rgft_d72bdead{0%{background-size:0 .1em}to{background-size:100% .1em}}[data-eb-6a8f3296] .rgft_8711ccd9 b,[data-eb-6a8f3296] b.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 strong,[data-eb-6a8f3296] strong.rgft_8711ccd9{font-weight:700}[data-eb-6a8f3296] i.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 i,[data-eb-6a8f3296] em.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 em{font-style:italic}[data-eb-6a8f3296] u.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 u{text-decoration:underline}[data-eb-6a8f3296] code.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 code{font-family:Amazon Ember Mono,Consolas,Andale Mono WT,Andale Mono,Lucida Console,Lucida Sans Typewriter,DejaVu Sans Mono,Bitstream Vera Sans Mono,Liberation Mono,Nimbus Mono L,Monaco,Courier New,Courier,monospace;border-radius:4px;border:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);color:var(--rg-color-text-secondary, #232B37);padding-top:var(--rg-padding-8);padding-right:var(--rg-padding-8);padding-bottom:var(--rg-padding-8);padding-left:var(--rg-padding-8)}[data-eb-6a8f3296] .rgft_12e1c6fa{display:inline!important;vertical-align:middle}[data-eb-6a8f3296] .rgft_8711ccd9 p img{aspect-ratio:16/9;height:100%;object-fit:cover;width:100%;border-radius:8px;order:1;margin-bottom:var(--rg-margin-4)}[data-eb-6a8f3296] .rgft_8711ccd9 table{table-layout:fixed;border-spacing:0;width:100%}[data-eb-6a8f3296] .rgft_8711ccd9 table td{font-size:14px;border-right:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-bottom:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);padding-top:var(--rg-padding-6);padding-right:var(--rg-padding-6);padding-bottom:var(--rg-padding-6);padding-left:var(--rg-padding-6)}[data-eb-6a8f3296] .rgft_8711ccd9 table td:first-of-type{border-left:1px solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table thead tr:first-of-type>*:first-of-type,[data-eb-6a8f3296] .rgft_8711ccd9 table:not(:has(thead)) tr:first-of-type>*:first-of-type{border-top-left-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table thead tr:first-of-type>*:last-of-type,[data-eb-6a8f3296] .rgft_8711ccd9 table:not(:has(thead)) tr:first-of-type>*:last-of-type{border-top-right-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table tr:last-of-type td:first-of-type{border-bottom-left-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table tr:last-of-type td:last-of-type{border-bottom-right-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table:not(:has(thead),:has(th)) tr:first-of-type td{border-top:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-bottom:1px solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table th{color:var(--rg-color-text-primary-inverted, #FFFFFF);min-width:280px;max-width:400px;padding:0;text-align:left;vertical-align:top;background-color:var(--rg-color-background-object-inverted, #232B37);border-left:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-bottom:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);padding-top:var(--rg-padding-6);padding-right:var(--rg-padding-6);padding-bottom:var(--rg-padding-6);padding-left:var(--rg-padding-6);row-gap:var(--rg-margin-5);column-gap:var(--rg-margin-5);max-width:100%;min-width:150px}@media (min-width: 480px) and (max-width: 767px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:100%;min-width:150px}}@media (min-width: 768px) and (max-width: 1023px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:240px;min-width:180px}}@media (min-width: 1024px) and (max-width: 1279px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:350px;min-width:240px}}@media (min-width: 1280px) and (max-width: 1599px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:400px;min-width:280px}}@media (min-width: 1600px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:400px;min-width:280px}}[data-eb-6a8f3296] .rgft_8711ccd9 table th:first-of-type{border-top-left-radius:16px;border-top:0 solid var(--rg-color-border-lowcontrast, #CCCCD1);border-left:0 solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:0 solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table th:nth-of-type(n+3){border-left:0 solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table th:last-of-type{border-top-right-radius:16px;border-top:0 solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:0 solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_a1b66739{display:inline-flex;flex-direction:column;align-items:center;justify-content:center;color:var(--rg-color-text-primary, #161D26);--icon-color: currentcolor}[data-eb-6a8f3296] .rgft_a1b66739.rgft_bc1a8743{height:16px;width:16px}[data-eb-6a8f3296] .rgft_a1b66739.rgft_c0cbb35d{height:20px;width:20px}[data-eb-6a8f3296] .rgft_a1b66739.rgft_bd40fe12{height:32px;width:32px}[data-eb-6a8f3296] .rgft_a1b66739.rgft_27320e58{height:48px;width:48px}[data-eb-6a8f3296] .rgft_a1b66739 svg{fill:none;stroke:none}[data-eb-6a8f3296] .rgft_a1b66739 path[data-fill]:not([fill]){fill:var(--icon-color)}[data-eb-6a8f3296] .rgft_a1b66739 path[data-stroke]{stroke-width:2}[data-eb-6a8f3296] .rgft_a1b66739 path[data-stroke]:not([stroke]){stroke:var(--icon-color)}[data-eb-6a8f3296] .rgft_3ed66ff4{display:inline-flex;flex-direction:column;align-items:center;justify-content:center;color:var(--rg-color-text-primary, #161D26)}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_9124b200{height:10px;width:10px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_bc1a8743{height:16px;width:16px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_c0cbb35d{height:20px;width:20px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_bd40fe12{height:32px;width:32px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_27320e58{height:48px;width:48px}[data-eb-6a8f3296] .rgft_98b54368{color:var(--rg-color-text-body, #232B37)}[data-eb-6a8f3296] .rgft_98b54368.rgft_275611e5{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_98b54368.rgft_275611e5{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_98b54368.rgft_275611e5{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_98b54368.rgft_275611e5{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_98b54368.rgft_275611e5{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_98b54368.rgft_275611e5{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_98b54368.rgft_275611e5{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_98b54368.rgft_275611e5{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_98b54368.rgft_007aef8b{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.429;font-weight:400;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_98b54368.rgft_007aef8b{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.429;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_98b54368.rgft_007aef8b{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.429;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_98b54368.rgft_007aef8b{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_98b54368.rgft_007aef8b{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_98b54368.rgft_007aef8b{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_98b54368.rgft_007aef8b{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_98b54368.rgft_007aef8b{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_98b54368.rgft_ff19c5f9{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:1.333;font-weight:400;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_98b54368.rgft_ff19c5f9{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:1.333;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_98b54368.rgft_ff19c5f9{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:1.333;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_98b54368.rgft_ff19c5f9{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_98b54368.rgft_ff19c5f9{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_98b54368.rgft_ff19c5f9{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_98b54368.rgft_ff19c5f9{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_98b54368.rgft_ff19c5f9{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_98b54368 ul{list-style-type:disc;margin-top:2rem}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee{display:inline;position:relative;cursor:pointer;text-decoration:none!important;color:var(--rg-color-link-default, #006CE0);background:linear-gradient(to right,currentcolor,currentcolor);background-size:100% .1em;background-position:0 100%;background-repeat:no-repeat}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee:focus-visible{color:var(--rg-color-link-focus, #006CE0)}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee:hover{color:var(--rg-color-link-hover, #003B8F);animation:rgft_9beb7cc5 .3s cubic-bezier(0,0,.2,1)}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee:visited{color:var(--rg-color-link-visited, #6842FF)}@keyframes rgft_9beb7cc5{0%{background-size:0 .1em}to{background-size:100% .1em}}[data-eb-6a8f3296] .rgft_d835af5c{color:var(--rg-color-text-title, #161D26)}[data-eb-6a8f3296] .rgft_d835af5c.rgft_3e9243e1{font-size:calc(4.5rem * var(--font-size-multiplier, 1.6));line-height:1.111;font-weight:500;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_3e9243e1{font-size:calc(3.75rem * var(--font-size-multiplier, 1.6));line-height:1.133;font-weight:500}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_3e9243e1{font-size:calc(3rem * var(--font-size-multiplier, 1.6));line-height:1.167;font-weight:500}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_d835af5c.rgft_3e9243e1{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_d835af5c.rgft_3e9243e1{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_d835af5c.rgft_3e9243e1{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_d835af5c.rgft_3e9243e1{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_d835af5c.rgft_3e9243e1{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_d835af5c.rgft_54816d41{font-size:calc(3.75rem * var(--font-size-multiplier, 1.6));line-height:1.133;font-weight:500;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_54816d41{font-size:calc(3rem * var(--font-size-multiplier, 1.6));line-height:1.167;font-weight:500}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_54816d41{font-size:calc(2.5rem * var(--font-size-multiplier, 1.6));line-height:1.2;font-weight:500}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_d835af5c.rgft_54816d41{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_d835af5c.rgft_54816d41{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_d835af5c.rgft_54816d41{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_d835af5c.rgft_54816d41{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_d835af5c.rgft_54816d41{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_d835af5c.rgft_852a8b78{font-size:calc(3rem * var(--font-size-multiplier, 1.6));line-height:1.167;font-weight:500;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_852a8b78{font-size:calc(2.5rem * var(--font-size-multiplier, 1.6));line-height:1.2;font-weight:500}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_852a8b78{font-size:calc(2rem * var(--font-size-multiplier, 1.6));line-height:1.25;font-weight:500}}[data-eb-6a8f3296] [data-rg-lang= | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---color | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://aws.amazon.com/blogs/big-data/amazon-emr-serverless-eliminates-local-storage-provisioning-reducing-data-processing-costs-by-up-to-20/ | Amazon EMR Serverless eliminates local storage provisioning, reducing data processing costs by up to 20% | AWS Big Data Blog Skip to Main Content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Blogs Home Blogs Editions AWS Big Data Blog Amazon EMR Serverless eliminates local storage provisioning, reducing data processing costs by up to 20% by Karthik Prabhakar , Matt Tolton , Neil Mukerje , and Ravi Kumar Singh on 06 JAN 2026 in Amazon EMR , Analytics , Announcements , Intermediate (200) , Serverless Permalink Comments Share At AWS re:Invent 2025, Amazon Web Services (AWS) announced serverless storage for Amazon EMR Serverless , a new capability that eliminates the need configure local disks for Apache Spark workloads. This reduces data processing costs by up to 20% while eliminating job failures from disk capacity constraints. With serverless storage, Amazon EMR Serverless automatically handles intermediate data operations, such as shuffle, on your behalf. You pay only for compute and memory—no storage charges. By decoupling storage from compute, Spark can release idle workers immediately, reducing costs throughout the job lifecycle. The following image shows the serverless storage for EMR Serverless announcement from the AWS re:Invent 2025 keynote: The challenge: Sizing local disk storage Running Apache Spark workloads requires sizing local disk storage for shuffle operations—where Spark redistributes data across executors during joins, aggregations, and sorts. This requires analyzing job histories to estimate disk requirements, leading to two common problems: overprovisioning wastes money on unused capacity, and under provisioning causes job failures when disk space runs out. Most customers overprovision local storage to ensure jobs complete successfully in production. Data skew compounds this further. When one executor handles a disproportionately large partition, that executor takes significantly longer to complete while other workers sit idle. If you didn’t provision enough disk for that skewed executor, the job fails entirely—making data skew one of the top causes of Spark job failures. However, the problem extends beyond capacity planning. Because shuffle data couples tightly to local disks, Spark executors pin to worker nodes even when compute requirements drop between job stages. This prevents Spark from releasing workers and scaling down, inflating compute costs throughout the job lifecycle. When a worker node fails, Spark must recompute the shuffle data stored on that node, causing delays and inefficient resource usage. How it works Serverless storage for Amazon EMR Serverless addresses these challenges by offloading shuffle operations from individual compute workers onto a separate, elastic storage layer. Instead of storing critical data on local disks attached to Spark executors, serverless storage automatically provisions and scales high-performance remote storage as your job runs. The architecture provides several key benefits. First, compute and storage scale independently—Spark can acquire and release workers as needed across job stages without worrying about preserving locally stored data. Second, shuffle data is evenly distributed across the serverless storage layer, eliminating data skew bottlenecks that occur when some executors handle disproportionately large shuffle partitions. Third, if a worker node fails, your job continues processing without delays or reruns because data is reliably stored outside individual compute workers. Serverless storage is provided at no additional charge, and it eliminates the cost associated with local storage. Instead of paying for fixed disk capacity sized for maximum potential I/O load—capacity that often sits idle during lighter workloads—you can use serverless storage without incurring storage costs. You can focus your budget on compute resources that directly process your data, not on managing and overprovisioning disk storage. Technical innovation brings three breakthroughs Serverless storage introduces three fundamental innovations that solve Spark’s shuffle bottlenecks: multi-tier aggregation architecture, purpose-built networking, and true storage-compute decoupling. Apache Spark’s shuffle mechanism has a core constraint: each mapper independently writes output as small files, and each reducer must fetch data from potentially thousands of workers. In a large-scale job with 10,000 mappers and 1,000 reducers, this creates 10 million individual data exchanges. Serverless storage aggregates early and intelligently—mappers stream data to an aggregation layer that consolidates shuffle data in memory before committing to storage. Whereas individual shuffle write and fetch operations might show slightly higher latency due to network round-trips compared to local disk I/O, the overall job performance improves by transforming millions of tiny I/O operations into a smaller number of large, sequential operations. Traditional Spark shuffle creates a mesh network where each worker maintains connections to potentially hundreds of other workers, spending significant CPU on connection management rather than data processing. We built a custom networking stack where each mapper opens a single persistent remote procedure call (RPC) connection to our aggregator layer, eliminating the mesh complexity. Although individual shuffle operations might show slightly higher latency due to network round trips compared to local disk I/O, overall job performance improves through better resource utilization and elastic scaling. Workers no longer run a shuffle service—they focus entirely on processing your data. Traditional Amazon EMR Serverless jobs store shuffle data on local disks, coupling data lifecycle to worker lifecycle—idle workers can’t terminate without losing shuffle data. Serverless storage decouples these entirely by storing shuffle data in AWS managed storage with opaque handles tracked by the driver. Workers can terminate immediately after completing tasks without data loss, enabling elastic scaling. In funnel-shaped queries where early stages require massive parallelism that narrows as data aggregates, we’re seeing up to 80% compute cost reduction in benchmarks by releasing idle workers instantly. The following diagram illustrates instant worker release in funnel-shaped queries. Our aggregator layer integrates directly with AWS Identity and Access Management (IAM), AWS Lake Formation , and fine-grained access control systems, providing job-level data isolation with access controls that match source data permissions. Getting started Serverless storage is available in multiple AWS Regions . For the current list of supported Regions, refer to the Amazon EMR User Guide . New applications Serverless storage can be enabled for new applications starting with Amazon EMR release 7.12. Follow these steps: Create an Amazon EMR Serverless application with Amazon EMR 7.12 or later: aws emr-serverless create-application \ --type "SPARK" \ --name my-application \ --release-label emr-7.12.0 \ --runtime-configuration '[{ "classification": "spark-defaults", "properties": { "spark.aws.serverlessStorage.enabled": "true" } }]' \ --region us-east-1 Submit your Spark job: aws emr-serverless start-job-run \ --application-id <application-id> \ --execution-role-arn <execution-role-arn> \ --job-driver '{ "sparkSubmit": { "entryPoint": "s3://<bucket>/<your_script.py>", "sparkSubmitParameters": "--conf spark.executor.cores=4 --conf spark.executor.memory=20g --conf spark.driver.cores=4 --conf spark.driver.memory=8g --conf spark.executor.instances=10" } }' Existing applications You can enable serverless storage for existing applications on Amazon EMR 7.12 or later by updating your application settings. To enable serverless storage using AWS Command Line Interface (AWS CLI), enter the following command: aws emr-serverless update-application \ --application-id <application-id> \ --runtime-configuration '[{ "classification": "spark-defaults", "properties": { "spark.aws.serverlessStorage.enabled": "true" } }]' To enable serverless storage using Amazon EMR Studio UI, navigate to your application in Amazon EMR Studio, go to Configuration , and add the Spark property spark.aws.serverlessStorage.enabled=true in the spark-defaults classification. Job-level configuration You can also enable serverless storage for specific jobs, even when it’s not enabled at the application level: aws emr-serverless start-job-run \ --application-id <application-id> \ --execution-role-arn <execution-role-arn> \ --job-driver '{ "sparkSubmit": { "entryPoint": "s3://<bucket>/<your_script.py>", "sparkSubmitParameters": "--conf spark.executor.cores=4 --conf spark.executor.memory=20g --conf spark.aws.serverlessStorage.enabled=true" } }' (Optional) Disabling serverless storage If you prefer to continue using local disks, you can disable serverless storage by omitting the spark.aws.serverlessStorage.enabled configuration or setting it to false at either the application or job level: spark.aws.serverlessStorage.enabled=false To use traditional local disk provisioning, configure the appropriate disk type and size for your application workers. Monitoring and cost tracking You can monitor elastic shuffle usage through standard Spark UI metrics and track costs at the application level in AWS Cost Explorer and AWS Cost and Usage Reports . The service automatically handles performance optimization and scaling, so you don’t need to tune configuration parameters. When to use serverless storage Serverless storage delivers the most value for workloads with substantial shuffle operations—typically jobs that shuffle more than 10 GB of data (and less than 200 G per job, the limitation as of this writing). These include: Large-scale data processing with heavy aggregations and joins Sort-heavy analytics workloads Iterative algorithms that repeatedly access the same datasets Jobs with unpredictable shuffle sizes benefit particularly well because serverless storage automatically scales capacity up and down based on real-time demand. For workloads with minimal shuffle activity or very short duration (under 2–3 minutes), the benefits might be limited. In these cases, the overhead of remote storage access might outweigh the advantages of elastic scaling. Security and data lifecycle Your data is stored in serverless storage only while your job is running and is automatically deleted when your job is completed. Because Amazon EMR Serverless batch jobs can run for up to 24 hours, your data will be stored for no longer than this maximum duration. Serverless storage encrypts your data both in transit between your Amazon EMR Serverless application and the serverless storage layer and at rest while temporarily stored, using AWS managed encryption keys. The service uses an IAM based security model with job-level data isolation, which means that one job can’t access the shuffle data of another job. Serverless storage maintains the same security standards as Amazon EMR Serverless, with enterprise-grade security controls throughout the processing lifecycle. Conclusion Serverless storage represents a fundamental shift in how we approach data processing infrastructure, eliminating manual configuration, aligning costs to actual usage, and improving reliability for I/O intensive workloads. By offloading shuffle operations to a managed service, data engineers can focus on building analytics rather than managing storage infrastructure. To learn more about serverless storage and get started, visit the Amazon EMR Serverless documentation . About the authors Karthik Prabhakar Karthik is a Data Processing Engines Architect for Amazon EMR at AWS. He specializes in distributed systems architecture and query optimization, working with customers to solve complex performance challenges in large-scale data processing workloads. His focus spans engine internals, cost optimization strategies, and architectural patterns that enable customers to run petabyte-scale analytics efficiently. Ravi Kumar Ravi is a Senior Product Manager Technical at Amazon Web Services, specializing in exabyte-scale data infrastructure and analytics platforms. He helps customers unlock insights from structured and unstructured data using open-source technologies and cloud computing. Outside of work, Ravi enjoys exploring emerging trends in data science and machine learning. Matt Tolton Matt is a Senior Principal Engineer at Amazon Web Services. Neil Mukerje Neil is a Principal Product Manager at Amazon Web Services. Loading comments… Resources Amazon Athena Amazon EMR Amazon Kinesis Amazon MSK Amazon QuickSight Amazon Redshift AWS Glue Follow Twitter Facebook LinkedIn Twitch Email Updates Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms Cookie Preferences © 2025, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute | Application binary interface - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [abi] Application binary interface (ABI) [abi .intro] This section documents features that affect the ABI of the compiled output of a crate. See extern functions for information on specifying the ABI for exporting functions. See external blocks for information on specifying the ABI for linking external libraries. [abi .used] The used attribute [abi .used .intro] The used attribute can only be applied to static items . This attribute forces the compiler to keep the variable in the output object file (.o, .rlib, etc. excluding final binaries) even if the variable is not used, or referenced, by any other item in the crate. However, the linker is still free to remove such an item. Below is an example that shows under what conditions the compiler keeps a static item in the output object file. #![allow(unused)] fn main() { // foo.rs // This is kept because of `#[used]`: #[used] static FOO: u32 = 0; // This is removable because it is unused: #[allow(dead_code)] static BAR: u32 = 0; // This is kept because it is publicly reachable: pub static BAZ: u32 = 0; // This is kept because it is referenced by a public, reachable function: static QUUX: u32 = 0; pub fn quux() -> &'static u32 { &QUUX } // This is removable because it is referenced by a private, unused (dead) function: static CORGE: u32 = 0; #[allow(dead_code)] fn corge() -> &'static u32 { &CORGE } } $ rustc -O --emit=obj --crate-type=rlib foo.rs $ nm -C foo.o 0000000000000000 R foo::BAZ 0000000000000000 r foo::FOO 0000000000000000 R foo::QUUX 0000000000000000 T foo::quux [abi .no_mangle] The no_mangle attribute [abi .no_mangle .intro] The no_mangle attribute may be used on any item to disable standard symbol name mangling. The symbol for the item will be the identifier of the item’s name. [abi .no_mangle .publicly-exported] Additionally, the item will be publicly exported from the produced library or object file, similar to the used attribute . [abi .no_mangle .unsafe] This attribute is unsafe as an unmangled symbol may collide with another symbol with the same name (or with a well-known symbol), leading to undefined behavior. #![allow(unused)] fn main() { #[unsafe(no_mangle)] extern "C" fn foo() {} } [abi .no_mangle .edition2024] 2024 Edition differences Before the 2024 edition it is allowed to use the no_mangle attribute without the unsafe qualification. [abi .link_section] The link_section attribute [abi .link_section .intro] The link_section attribute specifies the section of the object file that a function or static ’s content will be placed into. [abi .link_section .syntax] The link_section attribute uses the MetaNameValueStr syntax to specify the section name. #![allow(unused)] fn main() { #[unsafe(no_mangle)] #[unsafe(link_section = ".example_section")] pub static VAR1: u32 = 1; } [abi .link_section .unsafe] This attribute is unsafe as it allows users to place data and code into sections of memory not expecting them, such as mutable data into read-only areas. [abi .link_section .edition2024] 2024 Edition differences Before the 2024 edition it is allowed to use the link_section attribute without the unsafe qualification. [abi .export_name] The export_name attribute [abi .export_name .intro] The export_name attribute specifies the name of the symbol that will be exported on a function or static . [abi .export_name .syntax] The export_name attribute uses the MetaNameValueStr syntax to specify the symbol name. #![allow(unused)] fn main() { #[unsafe(export_name = "exported_symbol_name")] pub fn name_in_rust() { } } [abi .export_name .unsafe] This attribute is unsafe as a symbol with a custom name may collide with another symbol with the same name (or with a well-known symbol), leading to undefined behavior. [abi .export_name .edition2024] 2024 Edition differences Before the 2024 edition it is allowed to use the export_name attribute without the unsafe qualification. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/reference/config.html#config-relative-paths | Configuration - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book Configuration This document explains how Cargo’s configuration system works, as well as available keys or configuration. For configuration of a package through its manifest, see the manifest format . Hierarchical structure Cargo allows local configuration for a particular package as well as global configuration. It looks for configuration files in the current directory and all parent directories. If, for example, Cargo were invoked in /projects/foo/bar/baz , then the following configuration files would be probed for and unified in this order: /projects/foo/bar/baz/.cargo/config.toml /projects/foo/bar/.cargo/config.toml /projects/foo/.cargo/config.toml /projects/.cargo/config.toml /.cargo/config.toml $CARGO_HOME/config.toml which defaults to: Windows: %USERPROFILE%\.cargo\config.toml Unix: $HOME/.cargo/config.toml With this structure, you can specify configuration per-package, and even possibly check it into version control. You can also specify personal defaults with a configuration file in your home directory. If a key is specified in multiple config files, the values will get merged together. Numbers, strings, and booleans will use the value in the deeper config directory taking precedence over ancestor directories, where the home directory is the lowest priority. Arrays will be joined together with higher precedence items being placed later in the merged array. At present, when being invoked from a workspace, Cargo does not read config files from crates within the workspace. i.e. if a workspace has two crates in it, named /projects/foo/bar/baz/mylib and /projects/foo/bar/baz/mybin , and there are Cargo configs at /projects/foo/bar/baz/mylib/.cargo/config.toml and /projects/foo/bar/baz/mybin/.cargo/config.toml , Cargo does not read those configuration files if it is invoked from the workspace root ( /projects/foo/bar/baz/ ). Note: Cargo also reads config files without the .toml extension, such as .cargo/config . Support for the .toml extension was added in version 1.39 and is the preferred form. If both files exist, Cargo will use the file without the extension. Configuration format Configuration files are written in the TOML format (like the manifest), with simple key-value pairs inside of sections (tables). The following is a quick overview of all settings, with detailed descriptions found below. paths = ["/path/to/override"] # path dependency overrides [alias] # command aliases b = "build" c = "check" t = "test" r = "run" rr = "run --release" recursive_example = "rr --example recursions" space_example = ["run", "--release", "--", "\"command list\""] [build] jobs = 1 # number of parallel jobs, defaults to # of CPUs rustc = "rustc" # the rust compiler tool rustc-wrapper = "…" # run this wrapper instead of `rustc` rustc-workspace-wrapper = "…" # run this wrapper instead of `rustc` for workspace members rustdoc = "rustdoc" # the doc generator tool target = "triple" # build for the target triple (ignored by `cargo install`) target-dir = "target" # path of where to place generated artifacts build-dir = "target" # path of where to place intermediate build artifacts rustflags = ["…", "…"] # custom flags to pass to all compiler invocations rustdocflags = ["…", "…"] # custom flags to pass to rustdoc incremental = true # whether or not to enable incremental compilation dep-info-basedir = "…" # path for the base directory for targets in depfiles [credential-alias] # Provides a way to define aliases for credential providers. my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] [doc] browser = "chromium" # browser to use with `cargo doc --open`, # overrides the `BROWSER` environment variable [env] # Set ENV_VAR_NAME=value for any process run by Cargo ENV_VAR_NAME = "value" # Set even if already present in environment ENV_VAR_NAME_2 = { value = "value", force = true } # `value` is relative to the parent of `.cargo/config.toml`, env var will be the full absolute path ENV_VAR_NAME_3 = { value = "relative/path", relative = true } [future-incompat-report] frequency = 'always' # when to display a notification about a future incompat report [cache] auto-clean-frequency = "1 day" # How often to perform automatic cache cleaning [cargo-new] vcs = "none" # VCS to use ('git', 'hg', 'pijul', 'fossil', 'none') [http] debug = false # HTTP debugging proxy = "host:port" # HTTP proxy in libcurl format ssl-version = "tlsv1.3" # TLS version to use ssl-version.max = "tlsv1.3" # maximum TLS version ssl-version.min = "tlsv1.1" # minimum TLS version timeout = 30 # timeout for each HTTP request, in seconds low-speed-limit = 10 # network timeout threshold (bytes/sec) cainfo = "cert.pem" # path to Certificate Authority (CA) bundle proxy-cainfo = "cert.pem" # path to proxy Certificate Authority (CA) bundle check-revoke = true # check for SSL certificate revocation multiplexing = true # HTTP/2 multiplexing user-agent = "…" # the user-agent header [install] root = "/some/path" # `cargo install` destination directory [net] retry = 3 # network retries git-fetch-with-cli = true # use the `git` executable for git operations offline = true # do not access the network [net.ssh] known-hosts = ["..."] # known SSH host keys [patch.<registry>] # Same keys as for [patch] in Cargo.toml [profile.<name>] # Modify profile settings via config. inherits = "dev" # Inherits settings from [profile.dev]. opt-level = 0 # Optimization level. debug = true # Include debug info. split-debuginfo = '...' # Debug info splitting behavior. strip = "none" # Removes symbols or debuginfo. debug-assertions = true # Enables debug assertions. overflow-checks = true # Enables runtime integer overflow checks. lto = false # Sets link-time optimization. panic = 'unwind' # The panic strategy. incremental = true # Incremental compilation. codegen-units = 16 # Number of code generation units. rpath = false # Sets the rpath linking option. [profile.<name>.build-override] # Overrides build-script settings. # Same keys for a normal profile. [profile.<name>.package.<name>] # Override profile for a package. # Same keys for a normal profile (minus `panic`, `lto`, and `rpath`). [resolver] incompatible-rust-versions = "allow" # Specifies how resolver reacts to these [registries.<name>] # registries other than crates.io index = "…" # URL of the registry index token = "…" # authentication token for the registry credential-provider = "cargo:token" # The credential provider for this registry. [registries.crates-io] protocol = "sparse" # The protocol to use to access crates.io. [registry] default = "…" # name of the default registry token = "…" # authentication token for crates.io credential-provider = "cargo:token" # The credential provider for crates.io. global-credential-providers = ["cargo:token"] # The credential providers to use by default. [source.<name>] # source definition and replacement replace-with = "…" # replace this source with the given named source directory = "…" # path to a directory source registry = "…" # URL to a registry source local-registry = "…" # path to a local registry source git = "…" # URL of a git repository source branch = "…" # branch name for the git repository tag = "…" # tag name for the git repository rev = "…" # revision for the git repository [target.<triple>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` rustdocflags = ["…", "…"] # custom flags for `rustdoc` [target.<cfg>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` [target.<triple>.<links>] # `links` build script override rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] quiet = false # whether cargo output is quiet verbose = false # whether cargo provides verbose output color = 'auto' # whether cargo colorizes output hyperlinks = true # whether cargo inserts links into output unicode = true # whether cargo can render output using non-ASCII unicode characters progress.when = 'auto' # whether cargo shows progress bar progress.width = 80 # width of progress bar progress.term-integration = true # whether cargo reports progress to terminal emulator Environment variables Cargo can also be configured through environment variables in addition to the TOML configuration files. For each configuration key of the form foo.bar the environment variable CARGO_FOO_BAR can also be used to define the value. Keys are converted to uppercase, dots and dashes are converted to underscores. For example the target.x86_64-unknown-linux-gnu.runner key can also be defined by the CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER environment variable. Environment variables will take precedence over TOML configuration files. Currently only integer, boolean, string and some array values are supported to be defined by environment variables. Descriptions below indicate which keys support environment variables and otherwise they are not supported due to technical issues . In addition to the system above, Cargo recognizes a few other specific environment variables . Command-line overrides Cargo also accepts arbitrary configuration overrides through the --config command-line option. The argument should be in TOML syntax of KEY=VALUE or provided as a path to an extra configuration file: # With `KEY=VALUE` in TOML syntax cargo --config net.git-fetch-with-cli=true fetch # With a path to a configuration file cargo --config ./path/to/my/extra-config.toml fetch The --config option may be specified multiple times, in which case the values are merged in left-to-right order, using the same merging logic that is used when multiple configuration files apply. Configuration values specified this way take precedence over environment variables, which take precedence over configuration files. When the --config option is provided as an extra configuration file, The configuration file loaded this way follow the same precedence rules as other options specified directly with --config . Some examples of what it looks like using Bourne shell syntax: # Most shells will require escaping. cargo --config http.proxy=\"http://example.com\" … # Spaces may be used. cargo --config "net.git-fetch-with-cli = true" … # TOML array example. Single quotes make it easier to read and write. cargo --config 'build.rustdocflags = ["--html-in-header", "header.html"]' … # Example of a complex TOML key. cargo --config "target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))'.runner = 'my-runner'" … # Example of overriding a profile setting. cargo --config profile.dev.package.image.opt-level=3 … Config-relative paths Paths in config files may be absolute, relative, or a bare name without any path separators. Paths for executables without a path separator will use the PATH environment variable to search for the executable. Paths for non-executables will be relative to where the config value is defined. In particular, rules are: For environment variables, paths are relative to the current working directory. For config values loaded directly from the --config KEY=VALUE option, paths are relative to the current working directory. For config files, paths are relative to the parent directory of the directory where the config files were defined, no matter those files are from either the hierarchical probing or the --config <path> option. Note: To maintain consistency with existing .cargo/config.toml probing behavior, it is by design that a path in a config file passed via --config <path> is also relative to two levels up from the config file itself. To avoid unexpected results, the rule of thumb is putting your extra config files at the same level of discovered .cargo/config.toml in your project. For instance, given a project /my/project , it is recommended to put config files under /my/project/.cargo or a new directory at the same level, such as /my/project/.config . # Relative path examples. [target.x86_64-unknown-linux-gnu] runner = "foo" # Searches `PATH` for `foo`. [source.vendored-sources] # Directory is relative to the parent where `.cargo/config.toml` is located. # For example, `/my/project/.cargo/config.toml` would result in `/my/project/vendor`. directory = "vendor" Executable paths with arguments Some Cargo commands invoke external programs, which can be configured as a path and some number of arguments. The value may be an array of strings like ['/path/to/program', 'somearg'] or a space-separated string like '/path/to/program somearg' . If the path to the executable contains a space, the list form must be used. If Cargo is passing other arguments to the program such as a path to open or run, they will be passed after the last specified argument in the value of an option of this format. If the specified program does not have path separators, Cargo will search PATH for its executable. Credentials Configuration values with sensitive information are stored in the $CARGO_HOME/credentials.toml file. This file is automatically created and updated by cargo login and cargo logout when using the cargo:token credential provider. Tokens are used by some Cargo commands such as cargo publish for authenticating with remote registries. Care should be taken to protect the tokens and to keep them secret. It follows the same format as Cargo config files. [registry] token = "…" # Access token for crates.io [registries.<name>] token = "…" # Access token for the named registry As with most other config values, tokens may be specified with environment variables. The token for crates.io may be specified with the CARGO_REGISTRY_TOKEN environment variable. Tokens for other registries may be specified with environment variables of the form CARGO_REGISTRIES_<name>_TOKEN where <name> is the name of the registry in all capital letters. Note: Cargo also reads and writes credential files without the .toml extension, such as .cargo/credentials . Support for the .toml extension was added in version 1.39. In version 1.68, Cargo writes to the file with the extension by default. However, for backward compatibility reason, when both files exist, Cargo will read and write the file without the extension. Configuration keys This section documents all configuration keys. The description for keys with variable parts are annotated with angled brackets like target.<triple> where the <triple> part can be any target triple like target.x86_64-pc-windows-msvc . paths Type: array of strings (paths) Default: none Environment: not supported An array of paths to local packages which are to be used as overrides for dependencies. For more information see the Overriding Dependencies guide . [alias] Type: string or array of strings Default: see below Environment: CARGO_ALIAS_<name> The [alias] table defines CLI command aliases. For example, running cargo b is an alias for running cargo build . Each key in the table is the subcommand, and the value is the actual command to run. The value may be an array of strings, where the first element is the command and the following are arguments. It may also be a string, which will be split on spaces into subcommand and arguments. The following aliases are built-in to Cargo: [alias] b = "build" c = "check" d = "doc" t = "test" r = "run" rm = "remove" Aliases are not allowed to redefine existing built-in commands. Aliases are recursive: [alias] rr = "run --release" recursive_example = "rr --example recursions" [build] The [build] table controls build-time operations and compiler settings. build.jobs Type: integer or string Default: number of logical CPUs Environment: CARGO_BUILD_JOBS Sets the maximum number of compiler processes to run in parallel. If negative, it sets the maximum number of compiler processes to the number of logical CPUs plus provided value. Should not be 0. If a string default is provided, it sets the value back to defaults. Can be overridden with the --jobs CLI option. build.rustc Type: string (program path) Default: "rustc" Environment: CARGO_BUILD_RUSTC or RUSTC Sets the executable to use for rustc . build.rustc-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WRAPPER or RUSTC_WRAPPER Sets a wrapper to execute instead of rustc . The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). build.rustc-workspace-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER or RUSTC_WORKSPACE_WRAPPER Sets a wrapper to execute instead of rustc , for workspace members only. When building a single-package project without workspaces, that package is considered to be the workspace. The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). It affects the filename hash so that artifacts produced by the wrapper are cached separately. If both rustc-wrapper and rustc-workspace-wrapper are set, then they will be nested: the final invocation is $RUSTC_WRAPPER $RUSTC_WORKSPACE_WRAPPER $RUSTC . build.rustdoc Type: string (program path) Default: "rustdoc" Environment: CARGO_BUILD_RUSTDOC or RUSTDOC Sets the executable to use for rustdoc . build.target Type: string or array of strings Default: host platform Environment: CARGO_BUILD_TARGET The default target platform triples to compile to. Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. Can be overridden with the --target CLI option. [build] target = ["x86_64-unknown-linux-gnu", "i686-unknown-linux-gnu"] build.target-dir Type: string (path) Default: "target" Environment: CARGO_BUILD_TARGET_DIR or CARGO_TARGET_DIR The path to where all compiler output is placed. The default if not specified is a directory named target located at the root of the workspace. Can be overridden with the --target-dir CLI option. For more information see the build cache documentation . build.build-dir Type: string (path) Default: Defaults to the value of build.target-dir Environment: CARGO_BUILD_BUILD_DIR The directory where intermediate build artifacts will be stored. Intermediate artifacts are produced by Rustc/Cargo during the build process. This option supports path templating. Available template variables: {workspace-root} resolves to root of the current workspace. {cargo-cache-home} resolves to CARGO_HOME {workspace-path-hash} resolves to a hash of the manifest path For more information see the build cache documentation . build.rustflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS or RUSTFLAGS Extra command-line flags to pass to rustc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTFLAGS environment variable. RUSTFLAGS environment variable. All matching target.<triple>.rustflags and target.<cfg>.rustflags config entries joined together. build.rustflags config value. Additional flags may also be passed with the cargo rustc command. If the --target flag (or build.target ) is used, then the flags will only be passed to the compiler for the target. Things being built for the host, such as build scripts or proc macros, will not receive the args. Without --target , the flags will be passed to all compiler invocations (including build scripts and proc macros) because dependencies are shared. If you have args that you do not want to pass to build scripts or proc macros and are building for the host, pass --target with the host triple . It is not recommended to pass in flags that Cargo itself usually manages. For example, the flags driven by profiles are best handled by setting the appropriate profile setting. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.rustdocflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTDOCFLAGS or CARGO_ENCODED_RUSTDOCFLAGS or RUSTDOCFLAGS Extra command-line flags to pass to rustdoc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTDOCFLAGS environment variable. RUSTDOCFLAGS environment variable. All matching target.<triple>.rustdocflags config entries joined together. build.rustdocflags config value. Additional flags may also be passed with the cargo rustdoc command. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.incremental Type: bool Default: from profile Environment: CARGO_BUILD_INCREMENTAL or CARGO_INCREMENTAL Whether or not to perform incremental compilation . The default if not set is to use the value from the profile . Otherwise this overrides the setting of all profiles. The CARGO_INCREMENTAL environment variable can be set to 1 to force enable incremental compilation for all profiles, or 0 to disable it. This env var overrides the config setting. build.dep-info-basedir Type: string (path) Default: none Environment: CARGO_BUILD_DEP_INFO_BASEDIR Strips the given path prefix from dep info file paths. This config setting is intended to convert absolute paths to relative paths for tools that require relative paths. The setting itself is a config-relative path. So, for example, a value of "." would strip all paths starting with the parent directory of the .cargo directory. build.pipelining This option is deprecated and unused. Cargo always has pipelining enabled. [credential-alias] Type: string or array of strings Default: empty Environment: CARGO_CREDENTIAL_ALIAS_<name> The [credential-alias] table defines credential provider aliases. These aliases can be referenced as an element of the registry.global-credential-providers array, or as a credential provider for a specific registry under registries.<NAME>.credential-provider . If specified as a string, the value will be split on spaces into path and arguments. For example, to define an alias called my-alias : [credential-alias] my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] See Registry Authentication for more information. [doc] The [doc] table defines options for the cargo doc command. doc.browser Type: string or array of strings ( program path with args ) Default: BROWSER environment variable, or, if that is missing, opening the link in a system specific way This option sets the browser to be used by cargo doc , overriding the BROWSER environment variable when opening documentation with the --open option. [cargo-new] The [cargo-new] table defines defaults for the cargo new command. cargo-new.name This option is deprecated and unused. cargo-new.email This option is deprecated and unused. cargo-new.vcs Type: string Default: "git" or "none" Environment: CARGO_CARGO_NEW_VCS Specifies the source control system to use for initializing a new repository. Valid values are git , hg (for Mercurial), pijul , fossil or none to disable this behavior. Defaults to git , or none if already inside a VCS repository. Can be overridden with the --vcs CLI option. [env] The [env] section allows you to set additional environment variables for build scripts, rustc invocations, cargo run and cargo build . [env] OPENSSL_DIR = "/opt/openssl" By default, the variables specified will not override values that already exist in the environment. This behavior can be changed by setting the force flag. Setting the relative flag evaluates the value as a config-relative path that is relative to the parent directory of the .cargo directory that contains the config.toml file. The value of the environment variable will be the full absolute path. [env] TMPDIR = { value = "/home/tmp", force = true } OPENSSL_DIR = { value = "vendor/openssl", relative = true } [future-incompat-report] The [future-incompat-report] table controls setting for future incompat reporting future-incompat-report.frequency Type: string Default: "always" Environment: CARGO_FUTURE_INCOMPAT_REPORT_FREQUENCY Controls how often we display a notification to the terminal when a future incompat report is available. Possible values: always (default): Always display a notification when a command (e.g. cargo build ) produces a future incompat report never : Never display a notification [cache] The [cache] table defines settings for cargo’s caches. Global caches When running cargo commands, Cargo will automatically track which files you are using within the global cache. Periodically, Cargo will delete files that have not been used for some period of time. It will delete files that have to be downloaded from the network if they have not been used in 3 months. Files that can be generated without network access will be deleted if they have not been used in 1 month. The automatic deletion of files only occurs when running commands that are already doing a significant amount of work, such as all of the build commands ( cargo build , cargo test , cargo check , etc.), and cargo fetch . Automatic deletion is disabled if cargo is offline such as with --offline or --frozen to avoid deleting artifacts that may need to be used if you are offline for a long period of time. Note : This tracking is currently only implemented for the global cache in Cargo’s home directory. This includes registry indexes and source files downloaded from registries and git dependencies. Support for tracking build artifacts is not yet implemented, and tracked in cargo#13136 . Additionally, there is an unstable feature to support manually triggering cache cleaning, and to further customize the configuration options. See the Unstable chapter for more information. cache.auto-clean-frequency Type: string Default: "1 day" Environment: CARGO_CACHE_AUTO_CLEAN_FREQUENCY This option defines how often Cargo will automatically delete unused files in the global cache. This does not define how old the files must be, those thresholds are described above . It supports the following settings: "never" — Never deletes old files. "always" — Checks to delete old files every time Cargo runs. An integer followed by “seconds”, “minutes”, “hours”, “days”, “weeks”, or “months” — Checks to delete old files at most the given time frame. [http] The [http] table defines settings for HTTP behavior. This includes fetching crate dependencies and accessing remote git repositories. http.debug Type: boolean Default: false Environment: CARGO_HTTP_DEBUG If true , enables debugging of HTTP requests. The debug information can be seen by setting the CARGO_LOG=network=debug environment variable (or use network=trace for even more information). Be wary when posting logs from this output in a public location. The output may include headers with authentication tokens which you don’t want to leak! Be sure to review logs before posting them. http.proxy Type: string Default: none Environment: CARGO_HTTP_PROXY or HTTPS_PROXY or https_proxy or http_proxy Sets an HTTP and HTTPS proxy to use. The format is in libcurl format as in [protocol://]host[:port] . If not set, Cargo will also check the http.proxy setting in your global git configuration. If none of those are set, the HTTPS_PROXY or https_proxy environment variables set the proxy for HTTPS requests, and http_proxy sets it for HTTP requests. http.timeout Type: integer Default: 30 Environment: CARGO_HTTP_TIMEOUT or HTTP_TIMEOUT Sets the timeout for each HTTP request, in seconds. http.cainfo Type: string (path) Default: none Environment: CARGO_HTTP_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify TLS certificates. If not specified, Cargo attempts to use the system certificates. http.proxy-cainfo Type: string (path) Default: falls back to http.cainfo if not set Environment: CARGO_HTTP_PROXY_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify proxy TLS certificates. http.check-revoke Type: boolean Default: true (Windows) false (all others) Environment: CARGO_HTTP_CHECK_REVOKE This determines whether or not TLS certificate revocation checks should be performed. This only works on Windows. http.ssl-version Type: string or min/max table Default: none Environment: CARGO_HTTP_SSL_VERSION This sets the minimum TLS version to use. It takes a string, with one of the possible values of "default" , "tlsv1" , "tlsv1.0" , "tlsv1.1" , "tlsv1.2" , or "tlsv1.3" . This may alternatively take a table with two keys, min and max , which each take a string value of the same kind that specifies the minimum and maximum range of TLS versions to use. The default is a minimum version of "tlsv1.0" and a max of the newest version supported on your platform, typically "tlsv1.3" . http.low-speed-limit Type: integer Default: 10 Environment: CARGO_HTTP_LOW_SPEED_LIMIT This setting controls timeout behavior for slow connections. If the average transfer speed in bytes per second is below the given value for http.timeout seconds (default 30 seconds), then the connection is considered too slow and Cargo will abort and retry. http.multiplexing Type: boolean Default: true Environment: CARGO_HTTP_MULTIPLEXING When true , Cargo will attempt to use the HTTP2 protocol with multiplexing. This allows multiple requests to use the same connection, usually improving performance when fetching multiple files. If false , Cargo will use HTTP 1.1 without pipelining. http.user-agent Type: string Default: Cargo’s version Environment: CARGO_HTTP_USER_AGENT Specifies a custom user-agent header to use. The default if not specified is a string that includes Cargo’s version. [install] The [install] table defines defaults for the cargo install command. install.root Type: string (path) Default: Cargo’s home directory Environment: CARGO_INSTALL_ROOT Sets the path to the root directory for installing executables for cargo install . Executables go into a bin directory underneath the root. To track information of installed executables, some extra files, such as .crates.toml and .crates2.json , are also created under this root. The default if not specified is Cargo’s home directory (default .cargo in your home directory). Can be overridden with the --root command-line option. [net] The [net] table controls networking configuration. net.retry Type: integer Default: 3 Environment: CARGO_NET_RETRY Number of times to retry possibly spurious network errors. net.git-fetch-with-cli Type: boolean Default: false Environment: CARGO_NET_GIT_FETCH_WITH_CLI If this is true , then Cargo will use the git executable to fetch registry indexes and git dependencies. If false , then it uses a built-in git library. Setting this to true can be helpful if you have special authentication requirements that Cargo does not support. See Git Authentication for more information about setting up git authentication. net.offline Type: boolean Default: false Environment: CARGO_NET_OFFLINE If this is true , then Cargo will avoid accessing the network, and attempt to proceed with locally cached data. If false , Cargo will access the network as needed, and generate an error if it encounters a network error. Can be overridden with the --offline command-line option. net.ssh The [net.ssh] table contains settings for SSH connections. net.ssh.known-hosts Type: array of strings Default: see description Environment: not supported The known-hosts array contains a list of SSH host keys that should be accepted as valid when connecting to an SSH server (such as for SSH git dependencies). Each entry should be a string in a format similar to OpenSSH known_hosts files. Each string should start with one or more hostnames separated by commas, a space, the key type name, a space, and the base64-encoded key. For example: [net.ssh] known-hosts = [ "example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFO4Q5T0UV0SQevair9PFwoxY9dl4pQl3u5phoqJH3cF" ] Cargo will attempt to load known hosts keys from common locations supported in OpenSSH, and will join those with any listed in a Cargo configuration file. If any matching entry has the correct key, the connection will be allowed. Cargo comes with the host keys for github.com built-in. If those ever change, you can add the new keys to the config or known_hosts file. See Git Authentication for more details. [patch] Just as you can override dependencies using [patch] in Cargo.toml , you can override them in the cargo configuration file to apply those patches to any affected build. The format is identical to the one used in Cargo.toml . Since .cargo/config.toml files are not usually checked into source control, you should prefer patching using Cargo.toml where possible to ensure that other developers can compile your crate in their own environments. Patching through cargo configuration files is generally only appropriate when the patch section is automatically generated by an external build tool. If a given dependency is patched both in a cargo configuration file and a Cargo.toml file, the patch in the configuration file is used. If multiple configuration files patch the same dependency, standard cargo configuration merging is used, which prefers the value defined closest to the current directory, with $HOME/.cargo/config.toml taking the lowest precedence. Relative path dependencies in such a [patch] section are resolved relative to the configuration file they appear in. [profile] The [profile] table can be used to globally change profile settings, and override settings specified in Cargo.toml . It has the same syntax and options as profiles specified in Cargo.toml . See the Profiles chapter for details about the options. [profile.<name>.build-override] Environment: CARGO_PROFILE_<name>_BUILD_OVERRIDE_<key> The build-override table overrides settings for build scripts, proc macros, and their dependencies. It has the same keys as a normal profile. See the overrides section for more details. [profile.<name>.package.<name>] Environment: not supported The package table overrides settings for specific packages. It has the same keys as a normal profile, minus the panic , lto , and rpath settings. See the overrides section for more details. profile.<name>.codegen-units Type: integer Default: See profile docs. Environment: CARGO_PROFILE_<name>_CODEGEN_UNITS See codegen-units . profile.<name>.debug Type: integer or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG See debug . profile.<name>.split-debuginfo Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_SPLIT_DEBUGINFO See split-debuginfo . profile.<name>.debug-assertions Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG_ASSERTIONS See debug-assertions . profile.<name>.incremental Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_INCREMENTAL See incremental . profile.<name>.lto Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_LTO See lto . profile.<name>.overflow-checks Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_OVERFLOW_CHECKS See overflow-checks . profile.<name>.opt-level Type: integer or string Default: See profile docs. Environment: CARGO_PROFILE_<name>_OPT_LEVEL See opt-level . profile.<name>.panic Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_PANIC See panic . profile.<name>.rpath Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_RPATH See rpath . profile.<name>.strip Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_STRIP See strip . [resolver] The [resolver] table overrides dependency resolution behavior for local development (e.g. excludes cargo install ). resolver.incompatible-rust-versions Type: string Default: See resolver docs Environment: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS When resolving which version of a dependency to use, select how versions with incompatible package.rust-version s are treated. Values include: allow : treat rust-version -incompatible versions like any other version fallback : only consider rust-version -incompatible versions if no other version matched Can be overridden with --ignore-rust-version CLI option Setting the dependency’s version requirement higher than any version with a compatible rust-version Specifying the version to cargo update with --precise See the resolver chapter for more details. MSRV: allow is supported on any version fallback is respected as of 1.84 [registries] The [registries] table is used for specifying additional registries . It consists of a sub-table for each named registry. registries.<name>.index Type: string (url) Default: none Environment: CARGO_REGISTRIES_<name>_INDEX Specifies the URL of the index for the registry. registries.<name>.token Type: string Default: none Environment: CARGO_REGISTRIES_<name>_TOKEN Specifies the authentication token for the given registry. This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registries.<name>.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRIES_<name>_CREDENTIAL_PROVIDER Specifies the credential provider for the given registry. If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registries.crates-io.protocol Type: string Default: "sparse" Environment: CARGO_REGISTRIES_CRATES_IO_PROTOCOL Specifies the protocol used to access crates.io. Allowed values are git or sparse . git causes Cargo to clone the entire index of all packages ever published to crates.io from https://github.com/rust-lang/crates.io-index/ . This can have performance implications due to the size of the index. sparse is a newer protocol which uses HTTPS to download only what is necessary from https://index.crates.io/ . This can result in a significant performance improvement for resolving new dependencies in most situations. More information about registry protocols may be found in the Registries chapter . [registry] The [registry] table controls the default registry used when one is not specified. registry.index This value is no longer accepted and should not be used. registry.default Type: string Default: "crates-io" Environment: CARGO_REGISTRY_DEFAULT The name of the registry (from the registries table ) to use by default for registry commands like cargo publish . Can be overridden with the --registry command-line option. registry.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRY_CREDENTIAL_PROVIDER Specifies the credential provider for crates.io . If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registry.token Type: string Default: none Environment: CARGO_REGISTRY_TOKEN Specifies the authentication token for crates.io . This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registry.global-credential-providers Type: array Default: ["cargo:token"] Environment: CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS Specifies the list of global credential providers. If credential provider is not set for a specific registry using registries.<name>.credential-provider , Cargo will use the credential providers in this list. Providers toward the end of the list have precedence. Path and arguments are split on spaces. If the path or arguments contains spaces, the credential provider should be defined in the [credential-alias] table and referenced here by its alias. See Registry Authentication for more information. [source] The [source] table defines the registry sources available. See Source Replacement for more information. It consists of a sub-table for each named source. A source should only define one kind (directory, registry, local-registry, or git). source.<name>.replace-with Type: string Default: none Environment: not supported If set, replace this source with the given named source or named registry. source.<name>.directory Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a directory source. source.<name>.registry Type: string (url) Default: none Environment: not supported Sets the URL to use for a registry source. source.<name>.local-registry Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a local registry source. source.<name>.git Type: string (url) Default: none Environment: not supported Sets the URL to use for a git repository source. source.<name>.branch Type: string Default: none Environment: not supported Sets the branch name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.tag Type: string Default: none Environment: not supported Sets the tag name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.rev Type: string Default: none Environment: not supported Sets the revision to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. [target] The [target] table is used for specifying settings for specific platform targets. It consists of a sub-table which is either a platform triple or a cfg() expression . The given values will be used if the target platform matches either the <triple> value or the <cfg> expression. [target.thumbv7m-none-eabi] linker = "arm-none-eabi-gcc" runner = "my-emulator" rustflags = ["…", "…"] [target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "my-arm-wrapper" rustflags = ["…", "…"] cfg values come from those built-in to the compiler (run rustc --print=cfg to view) and extra --cfg flags passed to rustc (such as those defined in RUSTFLAGS ). Do not try to match on debug_assertions , test , Cargo features like feature="foo" , or values set by build scripts . If using a target spec JSON file, the <triple> value is the filename stem. For example --target foo/bar.json would match [target.bar] . target.<triple>.ar This option is deprecated and unused. target.<triple>.linker Type: string (program path) Default: none Environment: CARGO_TARGET_<triple>_LINKER Specifies the linker which is passed to rustc (via -C linker ) when the <triple> is being compiled for. By default, the linker is not overridden. target.<cfg>.linker This is similar to the target linker , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.runner Type: string or array of strings ( program path with args ) Default: none Environment: CARGO_TARGET_<triple>_RUNNER If a runner is provided, executables for the target <triple> will be executed by invoking the specified runner with the actual executable passed as an argument. This applies to cargo run , cargo test and cargo bench commands. By default, compiled executables are executed directly. target.<cfg>.runner This is similar to the target runner , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.rustflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustflags for more details on the different ways to specific extra flags. target.<cfg>.rustflags This is similar to the target rustflags , but using a cfg() expression . If several <cfg> and <triple> entries match the current target, the flags are joined together. target.<triple>.rustdocflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTDOCFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustdocflags for more details on the different ways to specific extra flags. target.<triple>.<links> The links sub-table provides a way to override a build script . When specified, the build script for the given links library will not be run, and the given values will be used instead. [target.x86_64-unknown-linux-gnu.foo] rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] The [term] table controls terminal output and interaction. term.quiet Type: boolean Default: false Environment: CARGO_TERM_QUIET Controls whether or not log messages are displayed by Cargo. Specifying the --quiet flag will override and force quiet output. Specifying the --verbose flag will override and disable quiet output. term.verbose Type: boolean Default: false Environment: CARGO_TERM_VERBOSE Controls whether or not extra detailed messages are displayed by Cargo. Specifying the --quiet flag will override and disable verbose output. Specifying the --verbose flag will override and force verbose output. term.color Type: string Default: "auto" Environment: CARGO_TERM_COLOR Controls whether or not colored output is used in the terminal. Possible values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. Can be overridden with the --color command-line option. term.hyperlinks Type: bool Default: auto-detect Environment: CARGO_TERM_HYPERLINKS Controls whether or not hyperlinks are used in the terminal. term.unicode Type: bool Default: auto-detect Environment: CARGO_TERM_UNICODE Control whether output can be rendered using non-ASCII unicode characters. term.progress.when Type: string Default: "auto" Environment: CARGO_TERM_PROGRESS_WHEN Controls whether or not progress bar is shown in the terminal. Possible values: auto (default): Intelligently guess whether to show progress bar. always : Always show progress bar. never : Never show progress bar. term.progress.width Type: integer Default: none Environment: CARGO_TERM_PROGRESS_WIDTH Sets the width for progress bar. term.progress.term-integration Type: bool Default: auto-detect Environment: CARGO_TERM_PROGRESS_TERM_INTEGRATION Report progress to the terminal emulator for display in places like the task bar. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#r-attributes.meta.syntax | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/statements.html | Statements - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [statement] Statements [statement .syntax] Syntax Statement → ; | Item | LetStatement | ExpressionStatement | OuterAttribute * MacroInvocationSemi Show Railroad Statement ; Item LetStatement ExpressionStatement OuterAttribute MacroInvocationSemi [statement .intro] A statement is a component of a block , which is in turn a component of an outer expression or function . [statement .kind] Rust has two kinds of statement: declaration statements and expression statements . [statement .decl] Declaration statements A declaration statement is one that introduces one or more names into the enclosing statement block. The declared names may denote new variables or new items . The two kinds of declaration statements are item declarations and let statements. [statement .item] Item declarations [statement .item .intro] An item declaration statement has a syntactic form identical to an item declaration within a module . [statement .item .scope] Declaring an item within a statement block restricts its scope to the block containing the statement. The item is not given a canonical path nor are any sub-items it may declare. [statement .item .associated-scope] The exception to this is that associated items defined by implementations are still accessible in outer scopes as long as the item and, if applicable, trait are accessible. It is otherwise identical in meaning to declaring the item inside a module. [statement .item .outer-generics] There is no implicit capture of the containing function’s generic parameters, parameters, and local variables. For example, inner may not access outer_var . #![allow(unused)] fn main() { fn outer() { let outer_var = true; fn inner() { /* outer_var is not in scope here */ } inner(); } } [statement .let] let statements [statement .let .syntax] Syntax LetStatement → OuterAttribute * let PatternNoTopAlt ( : Type ) ? ( = Expression | = Expression except LazyBooleanExpression or end with a } else BlockExpression ) ? ; Show Railroad LetStatement OuterAttribute let PatternNoTopAlt : Type = Expression = except LazyBooleanExpression or end with a `}` Expression else BlockExpression ; [statement .let .intro] A let statement introduces a new set of variables , given by a pattern . The pattern is followed optionally by a type annotation and then either ends, or is followed by an initializer expression plus an optional else block. [statement .let .inference] When no type annotation is given, the compiler will infer the type, or signal an error if insufficient type information is available for definite inference. [statement .let .scope] Any variables introduced by a variable declaration are visible from the point of declaration until the end of the enclosing block scope, except when they are shadowed by another variable declaration. [statement .let .constraint] If an else block is not present, the pattern must be irrefutable. If an else block is present, the pattern may be refutable. [statement .let .behavior] If the pattern does not match (this requires it to be refutable), the else block is executed. The else block must always diverge (evaluate to the never type ). #![allow(unused)] fn main() { let (mut v, w) = (vec![1, 2, 3], 42); // The bindings may be mut or const let Some(t) = v.pop() else { // Refutable patterns require an else block panic!(); // The else block must diverge }; let [u, v] = [v[0], v[1]] else { // This pattern is irrefutable, so the compiler // will lint as the else block is redundant. panic!(); }; } [statement .expr] Expression statements [statement .expr .syntax] Syntax ExpressionStatement → ExpressionWithoutBlock ; | ExpressionWithBlock ; ? Show Railroad ExpressionStatement ExpressionWithoutBlock ; ExpressionWithBlock ; [statement .expr .intro] An expression statement is one that evaluates an expression and ignores its result. As a rule, an expression statement’s purpose is to trigger the effects of evaluating its expression. [statement .expr .restriction-semicolon] An expression that consists of only a block expression or control flow expression, if used in a context where a statement is permitted, can omit the trailing semicolon. This can cause an ambiguity between it being parsed as a standalone statement and as a part of another expression; in this case, it is parsed as a statement. [statement .expr .constraint-block] The type of ExpressionWithBlock expressions when used as statements must be the unit type. #![allow(unused)] fn main() { let mut v = vec![1, 2, 3]; v.pop(); // Ignore the element returned from pop if v.is_empty() { v.push(5); } else { v.remove(0); } // Semicolon can be omitted. [1]; // Separate expression statement, not an indexing expression. } When the trailing semicolon is omitted, the result must be type () . #![allow(unused)] fn main() { // bad: the block's type is i32, not () // Error: expected `()` because of default return type // if true { // 1 // } // good: the block's type is i32 if true { 1 } else { 2 }; } [statement .attribute] Attributes on statements Statements accept outer attributes . The attributes that have meaning on a statement are cfg , and the lint check attributes . | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package--Z | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#r-attributes.meta.intro | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/std/macro.cfg.html | cfg in std - Rust This old browser is unsupported and will most likely display funky things. cfg std 1.92.0 (ded5c06cf 2025-12-08) cfg Sections Examples In crate std std Macro cfg Copy item path 1.38.0 · Source macro_rules! cfg { ($($cfg:tt)*) => { ... }; } Expand description Evaluates boolean combinations of configuration flags at compile-time. In addition to the #[cfg] attribute, this macro is provided to allow boolean expression evaluation of configuration flags. This frequently leads to less duplicated code. The syntax given to this macro is the same syntax as the cfg attribute. cfg! , unlike #[cfg] , does not remove any code and only evaluates to true or false. For example, all blocks in an if/else expression need to be valid when cfg! is used for the condition, regardless of what cfg! is evaluating. § Examples let my_directory = if cfg! (windows) { "windows-specific-directory" } else { "unix-directory" }; | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#r-attributes.intro | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#railroad-AttrInput | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#tool-attributes | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/appendix/glossary.html#artifact | Appendix: Glossary - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book Glossary Artifact An artifact is the file or set of files created as a result of the compilation process. This includes linkable libraries, executable binaries, and generated documentation. Cargo Cargo is the Rust package manager , and the primary topic of this book. Cargo.lock See lock file . Cargo.toml See manifest . Crate A Rust crate is either a library or an executable program, referred to as either a library crate or a binary crate , respectively. Every target defined for a Cargo package is a crate . Loosely, the term crate may refer to either the source code of the target or to the compiled artifact that the target produces. It may also refer to a compressed package fetched from a registry . The source code for a given crate may be subdivided into modules . Edition A Rust edition is a developmental landmark of the Rust language. The edition of a package is specified in the Cargo.toml manifest , and individual targets can specify which edition they use. See the Edition Guide for more information. Feature The meaning of feature depends on the context: A feature is a named flag which allows for conditional compilation. A feature can refer to an optional dependency, or an arbitrary name defined in a Cargo.toml manifest that can be checked within source code. Cargo has unstable feature flags which can be used to enable experimental behavior of Cargo itself. The Rust compiler and Rustdoc have their own unstable feature flags (see The Unstable Book and The Rustdoc Book ). CPU targets have target features which specify capabilities of a CPU. Index The index is the searchable list of crates in a registry . Lock file The Cargo.lock lock file is a file that captures the exact version of every dependency used in a workspace or package . It is automatically generated by Cargo. See Cargo.toml vs Cargo.lock . Manifest A manifest is a description of a package or a workspace in a file named Cargo.toml . A virtual manifest is a Cargo.toml file that only describes a workspace, and does not include a package. Member A member is a package that belongs to a workspace . Module Rust’s module system is used to organize code into logical units called modules , which provide isolated namespaces within the code. The source code for a given crate may be subdivided into one or more separate modules. This is usually done to organize the code into areas of related functionality or to control the visible scope (public/private) of symbols within the source (structs, functions, and so on). A Cargo.toml file is primarily concerned with the package it defines, its crates, and the packages of the crates on which they depend. Nevertheless, you will see the term “module” often when working with Rust, so you should understand its relationship to a given crate. Package A package is a collection of source files and a Cargo.toml manifest file which describes the package. A package has a name and version which is used for specifying dependencies between packages. A package contains multiple targets , each of which is a crate . The Cargo.toml file describes the type of the crates (binary or library) within the package, along with some metadata about each one — how each is to be built, what their direct dependencies are, etc., as described throughout this book. The package root is the directory where the package’s Cargo.toml manifest is located. (Compare with workspace root .) The package ID specification , or SPEC , is a string used to uniquely reference a specific version of a package from a specific source. Small to medium sized Rust projects will only need a single package, though it is common for them to have multiple crates. Larger projects may involve multiple packages, in which case Cargo workspaces can be used to manage common dependencies and other related metadata between the packages. Package manager Broadly speaking, a package manager is a program (or collection of related programs) in a software ecosystem that automates the process of obtaining, installing, and upgrading artifacts. Within a programming language ecosystem, a package manager is a developer-focused tool whose primary functionality is to download library artifacts and their dependencies from some central repository; this capability is often combined with the ability to perform software builds (by invoking the language-specific compiler). Cargo is the package manager within the Rust ecosystem. Cargo downloads your Rust package ’s dependencies ( artifacts known as crates ), compiles your packages, makes distributable packages, and (optionally) uploads them to crates.io , the Rust community’s package registry . Package registry See registry . Project Another name for a package . Registry A registry is a service that contains a collection of downloadable crates that can be installed or used as dependencies for a package . The default registry in the Rust ecosystem is crates.io . The registry has an index which contains a list of all crates, and tells Cargo how to download the crates that are needed. Source A source is a provider that contains crates that may be included as dependencies for a package . There are several kinds of sources: Registry source — See registry . Local registry source — A set of crates stored as compressed files on the filesystem. See Local Registry Sources . Directory source — A set of crates stored as uncompressed files on the filesystem. See Directory Sources . Path source — An individual package located on the filesystem (such as a path dependency ) or a set of multiple packages (such as path overrides ). Git source — Packages located in a git repository (such as a git dependency or git source ). See Source Replacement for more information. Spec See package ID specification . Target The meaning of the term target depends on the context: Cargo Target — Cargo packages consist of targets which correspond to artifacts that will be produced. Packages can have library, binary, example, test, and benchmark targets. The list of targets are configured in the Cargo.toml manifest , often inferred automatically by the directory layout of the source files. Target Directory — Cargo places built artifacts in the target directory. By default this is a directory named target at the workspace root, or the package root if not using a workspace. The directory may be changed with the --target-dir command-line option, the CARGO_TARGET_DIR environment variable , or the build.target-dir config option . For more information see the build cache documentation. Target Architecture — The OS and machine architecture for the built artifacts are typically referred to as a target . Target Triple — A triple is a specific format for specifying a target architecture. Triples may be referred to as a target triple which is the architecture for the artifact produced, and the host triple which is the architecture that the compiler is running on. The target triple can be specified with the --target command-line option or the build.target config option . The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> where: arch = The base CPU architecture, for example x86_64 , i686 , arm , thumb , mips , etc. sub = The CPU sub-architecture, for example arm has v7 , v7s , v5te , etc. vendor = The vendor, for example unknown , apple , pc , nvidia , etc. sys = The system name, for example linux , windows , darwin , etc. none is typically used for bare-metal without an OS. abi = The ABI, for example gnu , android , eabi , etc. Some parameters may be omitted. Run rustc --print target-list for a list of supported targets. Test Targets Cargo test targets generate binaries which help verify proper operation and correctness of code. There are two types of test artifacts: Unit test — A unit test is an executable binary compiled directly from a library or a binary target. It contains the entire contents of the library or binary code, and runs #[test] annotated functions, intended to verify individual units of code. Integration test target — An integration test target is an executable binary compiled from a test target which is a distinct crate whose source is located in the tests directory or specified by the [[test]] table in the Cargo.toml manifest . It is intended to only test the public API of a library, or execute a binary to verify its operation. Workspace A workspace is a collection of one or more packages that share common dependency resolution (with a shared Cargo.lock lock file ), output directory, and various settings such as profiles. A virtual workspace is a workspace where the root Cargo.toml manifest does not define a package, and only lists the workspace members . The workspace root is the directory where the workspace’s Cargo.toml manifest is located. (Compare with package root .) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/statements.html#expression-statements | Statements - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [statement] Statements [statement .syntax] Syntax Statement → ; | Item | LetStatement | ExpressionStatement | OuterAttribute * MacroInvocationSemi Show Railroad Statement ; Item LetStatement ExpressionStatement OuterAttribute MacroInvocationSemi [statement .intro] A statement is a component of a block , which is in turn a component of an outer expression or function . [statement .kind] Rust has two kinds of statement: declaration statements and expression statements . [statement .decl] Declaration statements A declaration statement is one that introduces one or more names into the enclosing statement block. The declared names may denote new variables or new items . The two kinds of declaration statements are item declarations and let statements. [statement .item] Item declarations [statement .item .intro] An item declaration statement has a syntactic form identical to an item declaration within a module . [statement .item .scope] Declaring an item within a statement block restricts its scope to the block containing the statement. The item is not given a canonical path nor are any sub-items it may declare. [statement .item .associated-scope] The exception to this is that associated items defined by implementations are still accessible in outer scopes as long as the item and, if applicable, trait are accessible. It is otherwise identical in meaning to declaring the item inside a module. [statement .item .outer-generics] There is no implicit capture of the containing function’s generic parameters, parameters, and local variables. For example, inner may not access outer_var . #![allow(unused)] fn main() { fn outer() { let outer_var = true; fn inner() { /* outer_var is not in scope here */ } inner(); } } [statement .let] let statements [statement .let .syntax] Syntax LetStatement → OuterAttribute * let PatternNoTopAlt ( : Type ) ? ( = Expression | = Expression except LazyBooleanExpression or end with a } else BlockExpression ) ? ; Show Railroad LetStatement OuterAttribute let PatternNoTopAlt : Type = Expression = except LazyBooleanExpression or end with a `}` Expression else BlockExpression ; [statement .let .intro] A let statement introduces a new set of variables , given by a pattern . The pattern is followed optionally by a type annotation and then either ends, or is followed by an initializer expression plus an optional else block. [statement .let .inference] When no type annotation is given, the compiler will infer the type, or signal an error if insufficient type information is available for definite inference. [statement .let .scope] Any variables introduced by a variable declaration are visible from the point of declaration until the end of the enclosing block scope, except when they are shadowed by another variable declaration. [statement .let .constraint] If an else block is not present, the pattern must be irrefutable. If an else block is present, the pattern may be refutable. [statement .let .behavior] If the pattern does not match (this requires it to be refutable), the else block is executed. The else block must always diverge (evaluate to the never type ). #![allow(unused)] fn main() { let (mut v, w) = (vec![1, 2, 3], 42); // The bindings may be mut or const let Some(t) = v.pop() else { // Refutable patterns require an else block panic!(); // The else block must diverge }; let [u, v] = [v[0], v[1]] else { // This pattern is irrefutable, so the compiler // will lint as the else block is redundant. panic!(); }; } [statement .expr] Expression statements [statement .expr .syntax] Syntax ExpressionStatement → ExpressionWithoutBlock ; | ExpressionWithBlock ; ? Show Railroad ExpressionStatement ExpressionWithoutBlock ; ExpressionWithBlock ; [statement .expr .intro] An expression statement is one that evaluates an expression and ignores its result. As a rule, an expression statement’s purpose is to trigger the effects of evaluating its expression. [statement .expr .restriction-semicolon] An expression that consists of only a block expression or control flow expression, if used in a context where a statement is permitted, can omit the trailing semicolon. This can cause an ambiguity between it being parsed as a standalone statement and as a part of another expression; in this case, it is parsed as a statement. [statement .expr .constraint-block] The type of ExpressionWithBlock expressions when used as statements must be the unit type. #![allow(unused)] fn main() { let mut v = vec![1, 2, 3]; v.pop(); // Ignore the element returned from pop if v.is_empty() { v.push(5); } else { v.remove(0); } // Semicolon can be omitted. [1]; // Separate expression statement, not an indexing expression. } When the trailing semicolon is omitted, the result must be type () . #![allow(unused)] fn main() { // bad: the block's type is i32, not () // Error: expected `()` because of default return type // if true { // 1 // } // good: the block's type is i32 if true { 1 } else { 2 }; } [statement .attribute] Attributes on statements Statements accept outer attributes . The attributes that have meaning on a statement are cfg , and the lint check attributes . | 2026-01-13T09:29:13 |
https://www.linkedin.com/uas/login?session_redirect=https%3A%2F%2Fwww%2Elinkedin%2Ecom%2Fposts%2Fryanheinrichs_userexperience-webdesign-uiux-activity-7408999842783395840--gY1&fromSignIn=true&trk=public_post_ellipsis-menu-semaphore-sign-in-redirect | LinkedIn Login, Sign in | LinkedIn Sign in Sign in with Apple Sign in with a passkey By clicking Continue, you agree to LinkedIn’s User Agreement , Privacy Policy , and Cookie Policy . or Email or phone Password Show Forgot password? Keep me logged in Sign in We’ve emailed a one-time link to your primary email address Click on the link to sign in instantly to your LinkedIn account. If you don’t see the email in your inbox, check your spam folder. Resend email Back New to LinkedIn? Join now Agree & Join LinkedIn By clicking Continue, you agree to LinkedIn’s User Agreement , Privacy Policy , and Cookie Policy . LinkedIn © 2026 User Agreement Privacy Policy Community Guidelines Cookie Policy Copyright Policy Send Feedback Language العربية (Arabic) বাংলা (Bangla) Čeština (Czech) Dansk (Danish) Deutsch (German) Ελληνικά (Greek) English (English) Español (Spanish) فارسی (Persian) Suomi (Finnish) Français (French) हिंदी (Hindi) Magyar (Hungarian) Bahasa Indonesia (Indonesian) Italiano (Italian) עברית (Hebrew) 日本語 (Japanese) 한국어 (Korean) मराठी (Marathi) Bahasa Malaysia (Malay) Nederlands (Dutch) Norsk (Norwegian) ਪੰਜਾਬੀ (Punjabi) Polski (Polish) Português (Portuguese) Română (Romanian) Русский (Russian) Svenska (Swedish) తెలుగు (Telugu) ภาษาไทย (Thai) Tagalog (Tagalog) Türkçe (Turkish) Українська (Ukrainian) Tiếng Việt (Vietnamese) 简体中文 (Chinese (Simplified)) 正體中文 (Chinese (Traditional)) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package--C | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes/codegen.html#the-naked-attribute | Code generation - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes .codegen] Code generation attributes The following attributes are used for controlling code generation. [attributes .codegen .inline] The inline attribute [attributes .codegen .inline .intro] The inline attribute suggests whether a copy of the attributed function’s code should be placed in the caller rather than generating a call to the function. Example #![allow(unused)] fn main() { #[inline] pub fn example1() {} #[inline(always)] pub fn example2() {} #[inline(never)] pub fn example3() {} } Note rustc automatically inlines functions when doing so seems worthwhile. Use this attribute carefully as poor decisions about what to inline can slow down programs. [attributes .codegen .inline .syntax] The syntax for the inline attribute is: Syntax InlineAttribute → inline ( always ) | inline ( never ) | inline Show Railroad InlineAttribute inline ( always ) inline ( never ) inline [attributes .codegen .inline .allowed-positions] The inline attribute may only be applied to functions with bodies — closures , async blocks , free functions , associated functions in an inherent impl or trait impl , and associated functions in a trait definition when those functions have a default definition . Note rustc ignores use in other positions but lints against it. This may become an error in the future. Note Though the attribute can be applied to closures and async blocks , the usefulness of this is limited as we do not yet support attributes on expressions. #![allow(unused)] fn main() { // We allow attributes on statements. #[inline] || (); // OK #[inline] async {}; // OK } #![allow(unused)] fn main() { // We don't yet allow attributes on expressions. let f = #[inline] || (); // ERROR } [attributes .codegen .inline .duplicates] Only the first use of inline on a function has effect. Note rustc lints against any use following the first. This may become an error in the future. [attributes .codegen .inline .modes] The inline attribute supports these modes: #[inline] suggests performing inline expansion. #[inline(always)] suggests that inline expansion should always be performed. #[inline(never)] suggests that inline expansion should never be performed. Note In every form the attribute is a hint. The compiler may ignore it. [attributes .codegen .inline .trait] When inline is applied to a function in a trait , it applies only to the code of the default definition . [attributes .codegen .inline .async] When inline is applied to an async function or async closure , it applies only to the code of the generated poll function. Note For more details, see Rust issue #129347 . [attributes .codegen .inline .externally-exported] The inline attribute is ignored if the function is externally exported with no_mangle or export_name . [attributes .codegen .cold] The cold attribute [attributes .codegen .cold .intro] Tests Tests with this rule: tests/codegen-llvm/cold-attribute.rs The cold attribute suggests that the attributed function is unlikely to be called which may help the compiler produce better code. Example #![allow(unused)] fn main() { #[cold] pub fn example() {} } [attributes .codegen .cold .syntax] The cold attribute uses the MetaWord syntax. [attributes .codegen .cold .allowed-positions] The cold attribute may only be applied to functions with bodies — closures , async blocks , free functions , associated functions in an inherent impl or trait impl , and associated functions in a trait definition when those functions have a default definition . Note rustc ignores use in other positions but lints against it. This may become an error in the future. Note Though the attribute can be applied to closures and async blocks , the usefulness of this is limited as we do not yet support attributes on expressions. [attributes .codegen .cold .duplicates] Only the first use of cold on a function has effect. Note rustc lints against any use following the first. This may become an error in the future. [attributes .codegen .cold .trait] Tests Tests with this rule: tests/codegen-llvm/cold-attribute.rs When cold is applied to a function in a trait , it applies only to the code of the default definition . [attributes .codegen .naked] The naked attribute [attributes .codegen .naked .intro] The naked attribute prevents the compiler from emitting a function prologue and epilogue for the attributed function. [attributes .codegen .naked .body] The function body must consist of exactly one naked_asm! macro invocation. [attributes .codegen .naked .prologue-epilogue] No function prologue or epilogue is generated for the attributed function. The assembly code in the naked_asm! block constitutes the full body of a naked function. [attributes .codegen .naked .unsafe-attribute] The naked attribute is an unsafe attribute . Annotating a function with #[unsafe(naked)] comes with the safety obligation that the body must respect the function’s calling convention, uphold its signature, and either return or diverge (i.e., not fall through past the end of the assembly code). [attributes .codegen .naked .call-stack] The assembly code may assume that the call stack and register state are valid on entry as per the signature and calling convention of the function. [attributes .codegen .naked .no-duplication] The assembly code may not be duplicated by the compiler except when monomorphizing polymorphic functions. Note Guaranteeing when the assembly code may or may not be duplicated is important for naked functions that define symbols. [attributes .codegen .naked .unused-variables] The unused_variables lint is suppressed within naked functions. [attributes .codegen .naked .inline] The inline attribute cannot by applied to a naked function. [attributes .codegen .naked .track_caller] The track_caller attribute cannot be applied to a naked function. [attributes .codegen .naked .testing] The testing attributes cannot be applied to a naked function. [attributes .codegen .no_builtins] The no_builtins attribute [attributes .codegen .no_builtins .intro] The no_builtins attribute disables optimization of certain code patterns related to calls to library functions that are assumed to exist. . --> Example #![allow(unused)] #![no_builtins] fn main() { } [attributes .codegen .no_builtins .syntax] The no_builtins attribute uses the MetaWord syntax. [attributes .codegen .no_builtins .allowed-positions] The no_builtins attribute can only be applied to the crate root. [attributes .codegen .no_builtins .duplicates] Only the first use of the no_builtins attribute has effect. Note rustc lints against any use following the first. [attributes .codegen .target_feature] The target_feature attribute [attributes .codegen .target_feature .intro] The target_feature attribute may be applied to a function to enable code generation of that function for specific platform architecture features. It uses the MetaListNameValueStr syntax with a single key of enable whose value is a string of comma-separated feature names to enable. #![allow(unused)] fn main() { #[cfg(target_feature = "avx2")] #[target_feature(enable = "avx2")] fn foo_avx2() {} } [attributes .codegen .target_feature .arch] Each target architecture has a set of features that may be enabled. It is an error to specify a feature for a target architecture that the crate is not being compiled for. [attributes .codegen .target_feature .closures] Closures defined within a target_feature -annotated function inherit the attribute from the enclosing function. [attributes .codegen .target_feature .target-ub] It is undefined behavior to call a function that is compiled with a feature that is not supported on the current platform the code is running on, except if the platform explicitly documents this to be safe. [attributes .codegen .target_feature .safety-restrictions] The following restrictions apply unless otherwise specified by the platform rules below: Safe #[target_feature] functions (and closures that inherit the attribute) can only be safely called within a caller that enables all the target_feature s that the callee enables. This restriction does not apply in an unsafe context. Safe #[target_feature] functions (and closures that inherit the attribute) can only be coerced to safe function pointers in contexts that enable all the target_feature s that the coercee enables. This restriction does not apply to unsafe function pointers. Implicitly enabled features are included in this rule. For example an sse2 function can call ones marked with sse . #![allow(unused)] fn main() { #[cfg(target_feature = "sse2")] { #[target_feature(enable = "sse")] fn foo_sse() {} fn bar() { // Calling `foo_sse` here is unsafe, as we must ensure that SSE is // available first, even if `sse` is enabled by default on the target // platform or manually enabled as compiler flags. unsafe { foo_sse(); } } #[target_feature(enable = "sse")] fn bar_sse() { // Calling `foo_sse` here is safe. foo_sse(); || foo_sse(); } #[target_feature(enable = "sse2")] fn bar_sse2() { // Calling `foo_sse` here is safe because `sse2` implies `sse`. foo_sse(); } } } [attributes .codegen .target_feature .fn-traits] A function with a #[target_feature] attribute never implements the Fn family of traits, although closures inheriting features from the enclosing function do. [attributes .codegen .target_feature .allowed-positions] The #[target_feature] attribute is not allowed on the following places: the main function a panic_handler function safe trait methods safe default functions in traits [attributes .codegen .target_feature .inline] Functions marked with target_feature are not inlined into a context that does not support the given features. The #[inline(always)] attribute may not be used with a target_feature attribute. [attributes .codegen .target_feature .availability] Available features The following is a list of the available feature names. [attributes .codegen .target_feature .x86] x86 or x86_64 Executing code with unsupported features is undefined behavior on this platform. Hence on this platform usage of #[target_feature] functions follows the above restrictions . Feature Implicitly Enables Description adx ADX — Multi-Precision Add-Carry Instruction Extensions aes sse2 AES — Advanced Encryption Standard avx sse4.2 AVX — Advanced Vector Extensions avx2 avx AVX2 — Advanced Vector Extensions 2 avx512bf16 avx512bw AVX512-BF16 — Advanced Vector Extensions 512-bit - Bfloat16 Extensions avx512bitalg avx512bw AVX512-BITALG — Advanced Vector Extensions 512-bit - Bit Algorithms avx512bw avx512f AVX512-BW — Advanced Vector Extensions 512-bit - Byte and Word Instructions avx512cd avx512f AVX512-CD — Advanced Vector Extensions 512-bit - Conflict Detection Instructions avx512dq avx512f AVX512-DQ — Advanced Vector Extensions 512-bit - Doubleword and Quadword Instructions avx512f avx2 , fma , f16c AVX512-F — Advanced Vector Extensions 512-bit - Foundation avx512fp16 avx512bw AVX512-FP16 — Advanced Vector Extensions 512-bit - Float16 Extensions avx512ifma avx512f AVX512-IFMA — Advanced Vector Extensions 512-bit - Integer Fused Multiply Add avx512vbmi avx512bw AVX512-VBMI — Advanced Vector Extensions 512-bit - Vector Byte Manipulation Instructions avx512vbmi2 avx512bw AVX512-VBMI2 — Advanced Vector Extensions 512-bit - Vector Byte Manipulation Instructions 2 avx512vl avx512f AVX512-VL — Advanced Vector Extensions 512-bit - Vector Length Extensions avx512vnni avx512f AVX512-VNNI — Advanced Vector Extensions 512-bit - Vector Neural Network Instructions avx512vp2intersect avx512f AVX512-VP2INTERSECT — Advanced Vector Extensions 512-bit - Vector Pair Intersection to a Pair of Mask Registers avx512vpopcntdq avx512f AVX512-VPOPCNTDQ — Advanced Vector Extensions 512-bit - Vector Population Count Instruction avxifma avx2 AVX-IFMA — Advanced Vector Extensions - Integer Fused Multiply Add avxneconvert avx2 AVX-NE-CONVERT — Advanced Vector Extensions - No-Exception Floating-Point conversion Instructions avxvnni avx2 AVX-VNNI — Advanced Vector Extensions - Vector Neural Network Instructions avxvnniint16 avx2 AVX-VNNI-INT16 — Advanced Vector Extensions - Vector Neural Network Instructions with 16-bit Integers avxvnniint8 avx2 AVX-VNNI-INT8 — Advanced Vector Extensions - Vector Neural Network Instructions with 8-bit Integers bmi1 BMI1 — Bit Manipulation Instruction Sets bmi2 BMI2 — Bit Manipulation Instruction Sets 2 cmpxchg16b cmpxchg16b — Compares and exchange 16 bytes (128 bits) of data atomically f16c avx F16C — 16-bit floating point conversion instructions fma avx FMA3 — Three-operand fused multiply-add fxsr fxsave and fxrstor — Save and restore x87 FPU, MMX Technology, and SSE State gfni sse2 GFNI — Galois Field New Instructions kl sse2 KEYLOCKER — Intel Key Locker Instructions lzcnt lzcnt — Leading zeros count movbe movbe — Move data after swapping bytes pclmulqdq sse2 pclmulqdq — Packed carry-less multiplication quadword popcnt popcnt — Count of bits set to 1 rdrand rdrand — Read random number rdseed rdseed — Read random seed sha sse2 SHA — Secure Hash Algorithm sha512 avx2 SHA512 — Secure Hash Algorithm with 512-bit digest sm3 avx SM3 — ShangMi 3 Hash Algorithm sm4 avx2 SM4 — ShangMi 4 Cipher Algorithm sse SSE — Streaming SIMD Extensions sse2 sse SSE2 — Streaming SIMD Extensions 2 sse3 sse2 SSE3 — Streaming SIMD Extensions 3 sse4.1 ssse3 SSE4.1 — Streaming SIMD Extensions 4.1 sse4.2 sse4.1 SSE4.2 — Streaming SIMD Extensions 4.2 sse4a sse3 SSE4a — Streaming SIMD Extensions 4a ssse3 sse3 SSSE3 — Supplemental Streaming SIMD Extensions 3 tbm TBM — Trailing Bit Manipulation vaes avx2 , aes VAES — Vector AES Instructions vpclmulqdq avx , pclmulqdq VPCLMULQDQ — Vector Carry-less multiplication of Quadwords widekl kl KEYLOCKER_WIDE — Intel Wide Keylocker Instructions xsave xsave — Save processor extended states xsavec xsavec — Save processor extended states with compaction xsaveopt xsaveopt — Save processor extended states optimized xsaves xsaves — Save processor extended states supervisor [attributes .codegen .target_feature .aarch64] aarch64 On this platform the usage of #[target_feature] functions follows the above restrictions . Further documentation on these features can be found in the ARM Architecture Reference Manual , or elsewhere on developer.arm.com . Note The following pairs of features should both be marked as enabled or disabled together if used: paca and pacg , which LLVM currently implements as one feature. Feature Implicitly Enables Feature Name aes neon FEAT_AES & FEAT_PMULL — Advanced SIMD AES & PMULL instructions bf16 FEAT_BF16 — BFloat16 instructions bti FEAT_BTI — Branch Target Identification crc FEAT_CRC — CRC32 checksum instructions dit FEAT_DIT — Data Independent Timing instructions dotprod neon FEAT_DotProd — Advanced SIMD Int8 dot product instructions dpb FEAT_DPB — Data cache clean to point of persistence dpb2 dpb FEAT_DPB2 — Data cache clean to point of deep persistence f32mm sve FEAT_F32MM — SVE single-precision FP matrix multiply instruction f64mm sve FEAT_F64MM — SVE double-precision FP matrix multiply instruction fcma neon FEAT_FCMA — Floating point complex number support fhm fp16 FEAT_FHM — Half-precision FP FMLAL instructions flagm FEAT_FLAGM — Conditional flag manipulation fp16 neon FEAT_FP16 — Half-precision FP data processing frintts FEAT_FRINTTS — Floating-point to int helper instructions i8mm FEAT_I8MM — Int8 Matrix Multiplication jsconv neon FEAT_JSCVT — JavaScript conversion instruction lor FEAT_LOR — Limited Ordering Regions extension lse FEAT_LSE — Large System Extensions mte FEAT_MTE & FEAT_MTE2 — Memory Tagging Extension neon FEAT_AdvSimd & FEAT_FP — Floating Point and Advanced SIMD extension paca FEAT_PAUTH — Pointer Authentication (address authentication) pacg FEAT_PAUTH — Pointer Authentication (generic authentication) pan FEAT_PAN — Privileged Access-Never extension pmuv3 FEAT_PMUv3 — Performance Monitors extension (v3) rand FEAT_RNG — Random Number Generator ras FEAT_RAS & FEAT_RASv1p1 — Reliability, Availability and Serviceability extension rcpc FEAT_LRCPC — Release consistent Processor Consistent rcpc2 rcpc FEAT_LRCPC2 — RcPc with immediate offsets rdm neon FEAT_RDM — Rounding Double Multiply accumulate sb FEAT_SB — Speculation Barrier sha2 neon FEAT_SHA1 & FEAT_SHA256 — Advanced SIMD SHA instructions sha3 sha2 FEAT_SHA512 & FEAT_SHA3 — Advanced SIMD SHA instructions sm4 neon FEAT_SM3 & FEAT_SM4 — Advanced SIMD SM3/4 instructions spe FEAT_SPE — Statistical Profiling Extension ssbs FEAT_SSBS & FEAT_SSBS2 — Speculative Store Bypass Safe sve neon FEAT_SVE — Scalable Vector Extension sve2 sve FEAT_SVE2 — Scalable Vector Extension 2 sve2-aes sve2 , aes FEAT_SVE_AES & FEAT_SVE_PMULL128 — SVE AES instructions sve2-bitperm sve2 FEAT_SVE2_BitPerm — SVE Bit Permute sve2-sha3 sve2 , sha3 FEAT_SVE2_SHA3 — SVE SHA3 instructions sve2-sm4 sve2 , sm4 FEAT_SVE2_SM4 — SVE SM4 instructions tme FEAT_TME — Transactional Memory Extension vh FEAT_VHE — Virtualization Host Extensions [attributes .codegen .target_feature .loongarch] loongarch On this platform the usage of #[target_feature] functions follows the above restrictions . Feature Implicitly Enables Description f F — Single-precision float-point instructions d f D — Double-precision float-point instructions frecipe FRECIPE — Reciprocal approximation instructions lasx lsx LASX — 256-bit vector instructions lbt LBT — Binary translation instructions lsx d LSX — 128-bit vector instructions lvz LVZ — Virtualization instructions [attributes .codegen .target_feature .riscv] riscv32 or riscv64 On this platform the usage of #[target_feature] functions follows the above restrictions . Further documentation on these features can be found in their respective specification. Many specifications are described in the RISC-V ISA Manual , version 20250508 , or in another manual hosted on the RISC-V GitHub Account . Feature Implicitly Enables Description a A — Atomic instructions c C — Compressed instructions m M — Integer Multiplication and Division instructions zba Zba — Address Generation instructions zbb Zbb — Basic bit-manipulation zbc zbkc Zbc — Carry-less multiplication zbkb Zbkb — Bit Manipulation Instructions for Cryptography zbkc Zbkc — Carry-less multiplication for Cryptography zbkx Zbkx — Crossbar permutations zbs Zbs — Single-bit instructions zk zkn , zkr , zks , zkt , zbkb , zbkc , zkbx Zk — Scalar Cryptography zkn zknd , zkne , zknh , zbkb , zbkc , zkbx Zkn — NIST Algorithm suite extension zknd Zknd — NIST Suite: AES Decryption zkne Zkne — NIST Suite: AES Encryption zknh Zknh — NIST Suite: Hash Function Instructions zkr Zkr — Entropy Source Extension zks zksed , zksh , zbkb , zbkc , zkbx Zks — ShangMi Algorithm Suite zksed Zksed — ShangMi Suite: SM4 Block Cipher Instructions zksh Zksh — ShangMi Suite: SM3 Hash Function Instructions zkt Zkt — Data Independent Execution Latency Subset [attributes .codegen .target_feature .wasm] wasm32 or wasm64 Safe #[target_feature] functions may always be used in safe contexts on Wasm platforms. It is impossible to cause undefined behavior via the #[target_feature] attribute because attempting to use instructions unsupported by the Wasm engine will fail at load time without the risk of being interpreted in a way different from what the compiler expected. Feature Implicitly Enables Description bulk-memory WebAssembly bulk memory operations proposal extended-const WebAssembly extended const expressions proposal mutable-globals WebAssembly mutable global proposal nontrapping-fptoint WebAssembly non-trapping float-to-int conversion proposal relaxed-simd simd128 WebAssembly relaxed simd proposal sign-ext WebAssembly sign extension operators Proposal simd128 WebAssembly simd proposal multivalue WebAssembly multivalue proposal reference-types WebAssembly reference-types proposal tail-call WebAssembly tail-call proposal [attributes .codegen .target_feature .info] Additional information [attributes .codegen .target_feature .remark-cfg] See the target_feature conditional compilation option for selectively enabling or disabling compilation of code based on compile-time settings. Note that this option is not affected by the target_feature attribute, and is only driven by the features enabled for the entire crate. [attributes .codegen .target_feature .remark-rt] See the is_x86_feature_detected or is_aarch64_feature_detected macros in the standard library for runtime feature detection on these platforms. Note rustc has a default set of features enabled for each target and CPU. The CPU may be chosen with the -C target-cpu flag. Individual features may be enabled or disabled for an entire crate with the -C target-feature flag. [attributes .codegen .track_caller] The track_caller attribute [attributes .codegen .track_caller .allowed-positions] The track_caller attribute may be applied to any function with "Rust" ABI with the exception of the entry point fn main . [attributes .codegen .track_caller .traits] When applied to functions and methods in trait declarations, the attribute applies to all implementations. If the trait provides a default implementation with the attribute, then the attribute also applies to override implementations. [attributes .codegen .track_caller .extern] When applied to a function in an extern block the attribute must also be applied to any linked implementations, otherwise undefined behavior results. When applied to a function which is made available to an extern block, the declaration in the extern block must also have the attribute, otherwise undefined behavior results. [attributes .codegen .track_caller .behavior] Behavior Applying the attribute to a function f allows code within f to get a hint of the Location of the “topmost” tracked call that led to f ’s invocation. At the point of observation, an implementation behaves as if it walks up the stack from f ’s frame to find the nearest frame of an unattributed function outer , and it returns the Location of the tracked call in outer . #![allow(unused)] fn main() { #[track_caller] fn f() { println!("{}", std::panic::Location::caller()); } } Note core provides core::panic::Location::caller for observing caller locations. It wraps the core::intrinsics::caller_location intrinsic implemented by rustc . Note Because the resulting Location is a hint, an implementation may halt its walk up the stack early. See Limitations for important caveats. Examples When f is called directly by calls_f , code in f observes its callsite within calls_f : #![allow(unused)] fn main() { #[track_caller] fn f() { println!("{}", std::panic::Location::caller()); } fn calls_f() { f(); // <-- f() prints this location } } When f is called by another attributed function g which is in turn called by calls_g , code in both f and g observes g ’s callsite within calls_g : #![allow(unused)] fn main() { #[track_caller] fn f() { println!("{}", std::panic::Location::caller()); } #[track_caller] fn g() { println!("{}", std::panic::Location::caller()); f(); } fn calls_g() { g(); // <-- g() prints this location twice, once itself and once from f() } } When g is called by another attributed function h which is in turn called by calls_h , all code in f , g , and h observes h ’s callsite within calls_h : #![allow(unused)] fn main() { #[track_caller] fn f() { println!("{}", std::panic::Location::caller()); } #[track_caller] fn g() { println!("{}", std::panic::Location::caller()); f(); } #[track_caller] fn h() { println!("{}", std::panic::Location::caller()); g(); } fn calls_h() { h(); // <-- prints this location three times, once itself, once from g(), once from f() } } And so on. [attributes .codegen .track_caller .limits] Limitations [attributes .codegen .track_caller .hint] This information is a hint and implementations are not required to preserve it. [attributes .codegen .track_caller .decay] In particular, coercing a function with #[track_caller] to a function pointer creates a shim which appears to observers to have been called at the attributed function’s definition site, losing actual caller information across virtual calls. A common example of this coercion is the creation of a trait object whose methods are attributed. Note The aforementioned shim for function pointers is necessary because rustc implements track_caller in a codegen context by appending an implicit parameter to the function ABI, but this would be unsound for an indirect call because the parameter is not a part of the function’s type and a given function pointer type may or may not refer to a function with the attribute. The creation of a shim hides the implicit parameter from callers of the function pointer, preserving soundness. [attributes .codegen .instruction_set] The instruction_set attribute [attributes .codegen .instruction_set .intro] The instruction_set attribute specifies the instruction set that a function will use during code generation. This allows mixing more than one instruction set in a single program. Example #[instruction_set(arm::a32)] fn arm_code() {} #[instruction_set(arm::t32)] fn thumb_code() {} [attributes .codegen .instruction_set .syntax] The instruction_set attribute uses the MetaListPaths syntax to specify a single path consisting of the architecture family name and instruction set name. [attributes .codegen .instruction_set .allowed-positions] The instruction_set attribute may only be applied to functions with bodies — closures , async blocks , free functions , associated functions in an inherent impl or trait impl , and associated functions in a trait definition when those functions have a default definition . Note rustc ignores use in other positions but lints against it. This may become an error in the future. Note Though the attribute can be applied to closures and async blocks , the usefulness of this is limited as we do not yet support attributes on expressions. [attributes .codegen .instruction_set .duplicates] The instruction_set attribute may be used only once on a function. [attributes .codegen .instruction_set .target-limits] The instruction_set attribute may only be used with a target that supports the given value. [attributes .codegen .instruction_set .inline-asm] When the instruction_set attribute is used, any inline assembly in the function must use the specified instruction set instead of the target default. [attributes .codegen .instruction_set .arm] instruction_set on ARM When targeting the ARMv4T and ARMv5te architectures, the supported values for instruction_set are: arm::a32 — Generate the function as A32 “ARM” code. arm::t32 — Generate the function as T32 “Thumb” code. If the address of the function is taken as a function pointer, the low bit of the address will depend on the selected instruction set: For arm::a32 (“ARM”), it will be 0. For arm::t32 (“Thumb”), it will be 1. | 2026-01-13T09:29:13 |
https://pt-br.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1v_OJQfV5Zcu-cblOHFXfPicMkZBPGWKUMR8y2VtHCkhFimX0DXmuO_lS7lSOvuxvJGvNENLC3hXctnK0aEhIreuGRGjRkAY5nzNTCCWlumoLGOzuQm7GYuIQhI_WWXvHN-cB9_Akw-iZt | Facebook Facebook Email ou telefone Senha Esqueceu a conta? Criar nova conta Você está bloqueado temporariamente Você está bloqueado temporariamente Parece que você estava usando este recurso de forma indevida. Bloqueamos temporariamente sua capacidade de usar o recurso. Back Português (Brasil) 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Français (France) Deutsch Cadastre-se Entrar Messenger Facebook Lite Vídeo Meta Pay Meta Store Meta Quest Ray-Ban Meta Meta AI Mais conteúdo da Meta AI Instagram Threads Central de Informações de Votação Política de Privacidade Central de Privacidade Sobre Criar anúncio Criar Página Desenvolvedores Carreiras Cookies Escolhas para anúncios Termos Ajuda Upload de contatos e não usuários Configurações Registro de atividades Meta © 2026 | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---help | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#options | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/reference/config.html#alias | Configuration - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book Configuration This document explains how Cargo’s configuration system works, as well as available keys or configuration. For configuration of a package through its manifest, see the manifest format . Hierarchical structure Cargo allows local configuration for a particular package as well as global configuration. It looks for configuration files in the current directory and all parent directories. If, for example, Cargo were invoked in /projects/foo/bar/baz , then the following configuration files would be probed for and unified in this order: /projects/foo/bar/baz/.cargo/config.toml /projects/foo/bar/.cargo/config.toml /projects/foo/.cargo/config.toml /projects/.cargo/config.toml /.cargo/config.toml $CARGO_HOME/config.toml which defaults to: Windows: %USERPROFILE%\.cargo\config.toml Unix: $HOME/.cargo/config.toml With this structure, you can specify configuration per-package, and even possibly check it into version control. You can also specify personal defaults with a configuration file in your home directory. If a key is specified in multiple config files, the values will get merged together. Numbers, strings, and booleans will use the value in the deeper config directory taking precedence over ancestor directories, where the home directory is the lowest priority. Arrays will be joined together with higher precedence items being placed later in the merged array. At present, when being invoked from a workspace, Cargo does not read config files from crates within the workspace. i.e. if a workspace has two crates in it, named /projects/foo/bar/baz/mylib and /projects/foo/bar/baz/mybin , and there are Cargo configs at /projects/foo/bar/baz/mylib/.cargo/config.toml and /projects/foo/bar/baz/mybin/.cargo/config.toml , Cargo does not read those configuration files if it is invoked from the workspace root ( /projects/foo/bar/baz/ ). Note: Cargo also reads config files without the .toml extension, such as .cargo/config . Support for the .toml extension was added in version 1.39 and is the preferred form. If both files exist, Cargo will use the file without the extension. Configuration format Configuration files are written in the TOML format (like the manifest), with simple key-value pairs inside of sections (tables). The following is a quick overview of all settings, with detailed descriptions found below. paths = ["/path/to/override"] # path dependency overrides [alias] # command aliases b = "build" c = "check" t = "test" r = "run" rr = "run --release" recursive_example = "rr --example recursions" space_example = ["run", "--release", "--", "\"command list\""] [build] jobs = 1 # number of parallel jobs, defaults to # of CPUs rustc = "rustc" # the rust compiler tool rustc-wrapper = "…" # run this wrapper instead of `rustc` rustc-workspace-wrapper = "…" # run this wrapper instead of `rustc` for workspace members rustdoc = "rustdoc" # the doc generator tool target = "triple" # build for the target triple (ignored by `cargo install`) target-dir = "target" # path of where to place generated artifacts build-dir = "target" # path of where to place intermediate build artifacts rustflags = ["…", "…"] # custom flags to pass to all compiler invocations rustdocflags = ["…", "…"] # custom flags to pass to rustdoc incremental = true # whether or not to enable incremental compilation dep-info-basedir = "…" # path for the base directory for targets in depfiles [credential-alias] # Provides a way to define aliases for credential providers. my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] [doc] browser = "chromium" # browser to use with `cargo doc --open`, # overrides the `BROWSER` environment variable [env] # Set ENV_VAR_NAME=value for any process run by Cargo ENV_VAR_NAME = "value" # Set even if already present in environment ENV_VAR_NAME_2 = { value = "value", force = true } # `value` is relative to the parent of `.cargo/config.toml`, env var will be the full absolute path ENV_VAR_NAME_3 = { value = "relative/path", relative = true } [future-incompat-report] frequency = 'always' # when to display a notification about a future incompat report [cache] auto-clean-frequency = "1 day" # How often to perform automatic cache cleaning [cargo-new] vcs = "none" # VCS to use ('git', 'hg', 'pijul', 'fossil', 'none') [http] debug = false # HTTP debugging proxy = "host:port" # HTTP proxy in libcurl format ssl-version = "tlsv1.3" # TLS version to use ssl-version.max = "tlsv1.3" # maximum TLS version ssl-version.min = "tlsv1.1" # minimum TLS version timeout = 30 # timeout for each HTTP request, in seconds low-speed-limit = 10 # network timeout threshold (bytes/sec) cainfo = "cert.pem" # path to Certificate Authority (CA) bundle proxy-cainfo = "cert.pem" # path to proxy Certificate Authority (CA) bundle check-revoke = true # check for SSL certificate revocation multiplexing = true # HTTP/2 multiplexing user-agent = "…" # the user-agent header [install] root = "/some/path" # `cargo install` destination directory [net] retry = 3 # network retries git-fetch-with-cli = true # use the `git` executable for git operations offline = true # do not access the network [net.ssh] known-hosts = ["..."] # known SSH host keys [patch.<registry>] # Same keys as for [patch] in Cargo.toml [profile.<name>] # Modify profile settings via config. inherits = "dev" # Inherits settings from [profile.dev]. opt-level = 0 # Optimization level. debug = true # Include debug info. split-debuginfo = '...' # Debug info splitting behavior. strip = "none" # Removes symbols or debuginfo. debug-assertions = true # Enables debug assertions. overflow-checks = true # Enables runtime integer overflow checks. lto = false # Sets link-time optimization. panic = 'unwind' # The panic strategy. incremental = true # Incremental compilation. codegen-units = 16 # Number of code generation units. rpath = false # Sets the rpath linking option. [profile.<name>.build-override] # Overrides build-script settings. # Same keys for a normal profile. [profile.<name>.package.<name>] # Override profile for a package. # Same keys for a normal profile (minus `panic`, `lto`, and `rpath`). [resolver] incompatible-rust-versions = "allow" # Specifies how resolver reacts to these [registries.<name>] # registries other than crates.io index = "…" # URL of the registry index token = "…" # authentication token for the registry credential-provider = "cargo:token" # The credential provider for this registry. [registries.crates-io] protocol = "sparse" # The protocol to use to access crates.io. [registry] default = "…" # name of the default registry token = "…" # authentication token for crates.io credential-provider = "cargo:token" # The credential provider for crates.io. global-credential-providers = ["cargo:token"] # The credential providers to use by default. [source.<name>] # source definition and replacement replace-with = "…" # replace this source with the given named source directory = "…" # path to a directory source registry = "…" # URL to a registry source local-registry = "…" # path to a local registry source git = "…" # URL of a git repository source branch = "…" # branch name for the git repository tag = "…" # tag name for the git repository rev = "…" # revision for the git repository [target.<triple>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` rustdocflags = ["…", "…"] # custom flags for `rustdoc` [target.<cfg>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` [target.<triple>.<links>] # `links` build script override rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] quiet = false # whether cargo output is quiet verbose = false # whether cargo provides verbose output color = 'auto' # whether cargo colorizes output hyperlinks = true # whether cargo inserts links into output unicode = true # whether cargo can render output using non-ASCII unicode characters progress.when = 'auto' # whether cargo shows progress bar progress.width = 80 # width of progress bar progress.term-integration = true # whether cargo reports progress to terminal emulator Environment variables Cargo can also be configured through environment variables in addition to the TOML configuration files. For each configuration key of the form foo.bar the environment variable CARGO_FOO_BAR can also be used to define the value. Keys are converted to uppercase, dots and dashes are converted to underscores. For example the target.x86_64-unknown-linux-gnu.runner key can also be defined by the CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER environment variable. Environment variables will take precedence over TOML configuration files. Currently only integer, boolean, string and some array values are supported to be defined by environment variables. Descriptions below indicate which keys support environment variables and otherwise they are not supported due to technical issues . In addition to the system above, Cargo recognizes a few other specific environment variables . Command-line overrides Cargo also accepts arbitrary configuration overrides through the --config command-line option. The argument should be in TOML syntax of KEY=VALUE or provided as a path to an extra configuration file: # With `KEY=VALUE` in TOML syntax cargo --config net.git-fetch-with-cli=true fetch # With a path to a configuration file cargo --config ./path/to/my/extra-config.toml fetch The --config option may be specified multiple times, in which case the values are merged in left-to-right order, using the same merging logic that is used when multiple configuration files apply. Configuration values specified this way take precedence over environment variables, which take precedence over configuration files. When the --config option is provided as an extra configuration file, The configuration file loaded this way follow the same precedence rules as other options specified directly with --config . Some examples of what it looks like using Bourne shell syntax: # Most shells will require escaping. cargo --config http.proxy=\"http://example.com\" … # Spaces may be used. cargo --config "net.git-fetch-with-cli = true" … # TOML array example. Single quotes make it easier to read and write. cargo --config 'build.rustdocflags = ["--html-in-header", "header.html"]' … # Example of a complex TOML key. cargo --config "target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))'.runner = 'my-runner'" … # Example of overriding a profile setting. cargo --config profile.dev.package.image.opt-level=3 … Config-relative paths Paths in config files may be absolute, relative, or a bare name without any path separators. Paths for executables without a path separator will use the PATH environment variable to search for the executable. Paths for non-executables will be relative to where the config value is defined. In particular, rules are: For environment variables, paths are relative to the current working directory. For config values loaded directly from the --config KEY=VALUE option, paths are relative to the current working directory. For config files, paths are relative to the parent directory of the directory where the config files were defined, no matter those files are from either the hierarchical probing or the --config <path> option. Note: To maintain consistency with existing .cargo/config.toml probing behavior, it is by design that a path in a config file passed via --config <path> is also relative to two levels up from the config file itself. To avoid unexpected results, the rule of thumb is putting your extra config files at the same level of discovered .cargo/config.toml in your project. For instance, given a project /my/project , it is recommended to put config files under /my/project/.cargo or a new directory at the same level, such as /my/project/.config . # Relative path examples. [target.x86_64-unknown-linux-gnu] runner = "foo" # Searches `PATH` for `foo`. [source.vendored-sources] # Directory is relative to the parent where `.cargo/config.toml` is located. # For example, `/my/project/.cargo/config.toml` would result in `/my/project/vendor`. directory = "vendor" Executable paths with arguments Some Cargo commands invoke external programs, which can be configured as a path and some number of arguments. The value may be an array of strings like ['/path/to/program', 'somearg'] or a space-separated string like '/path/to/program somearg' . If the path to the executable contains a space, the list form must be used. If Cargo is passing other arguments to the program such as a path to open or run, they will be passed after the last specified argument in the value of an option of this format. If the specified program does not have path separators, Cargo will search PATH for its executable. Credentials Configuration values with sensitive information are stored in the $CARGO_HOME/credentials.toml file. This file is automatically created and updated by cargo login and cargo logout when using the cargo:token credential provider. Tokens are used by some Cargo commands such as cargo publish for authenticating with remote registries. Care should be taken to protect the tokens and to keep them secret. It follows the same format as Cargo config files. [registry] token = "…" # Access token for crates.io [registries.<name>] token = "…" # Access token for the named registry As with most other config values, tokens may be specified with environment variables. The token for crates.io may be specified with the CARGO_REGISTRY_TOKEN environment variable. Tokens for other registries may be specified with environment variables of the form CARGO_REGISTRIES_<name>_TOKEN where <name> is the name of the registry in all capital letters. Note: Cargo also reads and writes credential files without the .toml extension, such as .cargo/credentials . Support for the .toml extension was added in version 1.39. In version 1.68, Cargo writes to the file with the extension by default. However, for backward compatibility reason, when both files exist, Cargo will read and write the file without the extension. Configuration keys This section documents all configuration keys. The description for keys with variable parts are annotated with angled brackets like target.<triple> where the <triple> part can be any target triple like target.x86_64-pc-windows-msvc . paths Type: array of strings (paths) Default: none Environment: not supported An array of paths to local packages which are to be used as overrides for dependencies. For more information see the Overriding Dependencies guide . [alias] Type: string or array of strings Default: see below Environment: CARGO_ALIAS_<name> The [alias] table defines CLI command aliases. For example, running cargo b is an alias for running cargo build . Each key in the table is the subcommand, and the value is the actual command to run. The value may be an array of strings, where the first element is the command and the following are arguments. It may also be a string, which will be split on spaces into subcommand and arguments. The following aliases are built-in to Cargo: [alias] b = "build" c = "check" d = "doc" t = "test" r = "run" rm = "remove" Aliases are not allowed to redefine existing built-in commands. Aliases are recursive: [alias] rr = "run --release" recursive_example = "rr --example recursions" [build] The [build] table controls build-time operations and compiler settings. build.jobs Type: integer or string Default: number of logical CPUs Environment: CARGO_BUILD_JOBS Sets the maximum number of compiler processes to run in parallel. If negative, it sets the maximum number of compiler processes to the number of logical CPUs plus provided value. Should not be 0. If a string default is provided, it sets the value back to defaults. Can be overridden with the --jobs CLI option. build.rustc Type: string (program path) Default: "rustc" Environment: CARGO_BUILD_RUSTC or RUSTC Sets the executable to use for rustc . build.rustc-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WRAPPER or RUSTC_WRAPPER Sets a wrapper to execute instead of rustc . The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). build.rustc-workspace-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER or RUSTC_WORKSPACE_WRAPPER Sets a wrapper to execute instead of rustc , for workspace members only. When building a single-package project without workspaces, that package is considered to be the workspace. The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). It affects the filename hash so that artifacts produced by the wrapper are cached separately. If both rustc-wrapper and rustc-workspace-wrapper are set, then they will be nested: the final invocation is $RUSTC_WRAPPER $RUSTC_WORKSPACE_WRAPPER $RUSTC . build.rustdoc Type: string (program path) Default: "rustdoc" Environment: CARGO_BUILD_RUSTDOC or RUSTDOC Sets the executable to use for rustdoc . build.target Type: string or array of strings Default: host platform Environment: CARGO_BUILD_TARGET The default target platform triples to compile to. Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. Can be overridden with the --target CLI option. [build] target = ["x86_64-unknown-linux-gnu", "i686-unknown-linux-gnu"] build.target-dir Type: string (path) Default: "target" Environment: CARGO_BUILD_TARGET_DIR or CARGO_TARGET_DIR The path to where all compiler output is placed. The default if not specified is a directory named target located at the root of the workspace. Can be overridden with the --target-dir CLI option. For more information see the build cache documentation . build.build-dir Type: string (path) Default: Defaults to the value of build.target-dir Environment: CARGO_BUILD_BUILD_DIR The directory where intermediate build artifacts will be stored. Intermediate artifacts are produced by Rustc/Cargo during the build process. This option supports path templating. Available template variables: {workspace-root} resolves to root of the current workspace. {cargo-cache-home} resolves to CARGO_HOME {workspace-path-hash} resolves to a hash of the manifest path For more information see the build cache documentation . build.rustflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS or RUSTFLAGS Extra command-line flags to pass to rustc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTFLAGS environment variable. RUSTFLAGS environment variable. All matching target.<triple>.rustflags and target.<cfg>.rustflags config entries joined together. build.rustflags config value. Additional flags may also be passed with the cargo rustc command. If the --target flag (or build.target ) is used, then the flags will only be passed to the compiler for the target. Things being built for the host, such as build scripts or proc macros, will not receive the args. Without --target , the flags will be passed to all compiler invocations (including build scripts and proc macros) because dependencies are shared. If you have args that you do not want to pass to build scripts or proc macros and are building for the host, pass --target with the host triple . It is not recommended to pass in flags that Cargo itself usually manages. For example, the flags driven by profiles are best handled by setting the appropriate profile setting. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.rustdocflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTDOCFLAGS or CARGO_ENCODED_RUSTDOCFLAGS or RUSTDOCFLAGS Extra command-line flags to pass to rustdoc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTDOCFLAGS environment variable. RUSTDOCFLAGS environment variable. All matching target.<triple>.rustdocflags config entries joined together. build.rustdocflags config value. Additional flags may also be passed with the cargo rustdoc command. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.incremental Type: bool Default: from profile Environment: CARGO_BUILD_INCREMENTAL or CARGO_INCREMENTAL Whether or not to perform incremental compilation . The default if not set is to use the value from the profile . Otherwise this overrides the setting of all profiles. The CARGO_INCREMENTAL environment variable can be set to 1 to force enable incremental compilation for all profiles, or 0 to disable it. This env var overrides the config setting. build.dep-info-basedir Type: string (path) Default: none Environment: CARGO_BUILD_DEP_INFO_BASEDIR Strips the given path prefix from dep info file paths. This config setting is intended to convert absolute paths to relative paths for tools that require relative paths. The setting itself is a config-relative path. So, for example, a value of "." would strip all paths starting with the parent directory of the .cargo directory. build.pipelining This option is deprecated and unused. Cargo always has pipelining enabled. [credential-alias] Type: string or array of strings Default: empty Environment: CARGO_CREDENTIAL_ALIAS_<name> The [credential-alias] table defines credential provider aliases. These aliases can be referenced as an element of the registry.global-credential-providers array, or as a credential provider for a specific registry under registries.<NAME>.credential-provider . If specified as a string, the value will be split on spaces into path and arguments. For example, to define an alias called my-alias : [credential-alias] my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] See Registry Authentication for more information. [doc] The [doc] table defines options for the cargo doc command. doc.browser Type: string or array of strings ( program path with args ) Default: BROWSER environment variable, or, if that is missing, opening the link in a system specific way This option sets the browser to be used by cargo doc , overriding the BROWSER environment variable when opening documentation with the --open option. [cargo-new] The [cargo-new] table defines defaults for the cargo new command. cargo-new.name This option is deprecated and unused. cargo-new.email This option is deprecated and unused. cargo-new.vcs Type: string Default: "git" or "none" Environment: CARGO_CARGO_NEW_VCS Specifies the source control system to use for initializing a new repository. Valid values are git , hg (for Mercurial), pijul , fossil or none to disable this behavior. Defaults to git , or none if already inside a VCS repository. Can be overridden with the --vcs CLI option. [env] The [env] section allows you to set additional environment variables for build scripts, rustc invocations, cargo run and cargo build . [env] OPENSSL_DIR = "/opt/openssl" By default, the variables specified will not override values that already exist in the environment. This behavior can be changed by setting the force flag. Setting the relative flag evaluates the value as a config-relative path that is relative to the parent directory of the .cargo directory that contains the config.toml file. The value of the environment variable will be the full absolute path. [env] TMPDIR = { value = "/home/tmp", force = true } OPENSSL_DIR = { value = "vendor/openssl", relative = true } [future-incompat-report] The [future-incompat-report] table controls setting for future incompat reporting future-incompat-report.frequency Type: string Default: "always" Environment: CARGO_FUTURE_INCOMPAT_REPORT_FREQUENCY Controls how often we display a notification to the terminal when a future incompat report is available. Possible values: always (default): Always display a notification when a command (e.g. cargo build ) produces a future incompat report never : Never display a notification [cache] The [cache] table defines settings for cargo’s caches. Global caches When running cargo commands, Cargo will automatically track which files you are using within the global cache. Periodically, Cargo will delete files that have not been used for some period of time. It will delete files that have to be downloaded from the network if they have not been used in 3 months. Files that can be generated without network access will be deleted if they have not been used in 1 month. The automatic deletion of files only occurs when running commands that are already doing a significant amount of work, such as all of the build commands ( cargo build , cargo test , cargo check , etc.), and cargo fetch . Automatic deletion is disabled if cargo is offline such as with --offline or --frozen to avoid deleting artifacts that may need to be used if you are offline for a long period of time. Note : This tracking is currently only implemented for the global cache in Cargo’s home directory. This includes registry indexes and source files downloaded from registries and git dependencies. Support for tracking build artifacts is not yet implemented, and tracked in cargo#13136 . Additionally, there is an unstable feature to support manually triggering cache cleaning, and to further customize the configuration options. See the Unstable chapter for more information. cache.auto-clean-frequency Type: string Default: "1 day" Environment: CARGO_CACHE_AUTO_CLEAN_FREQUENCY This option defines how often Cargo will automatically delete unused files in the global cache. This does not define how old the files must be, those thresholds are described above . It supports the following settings: "never" — Never deletes old files. "always" — Checks to delete old files every time Cargo runs. An integer followed by “seconds”, “minutes”, “hours”, “days”, “weeks”, or “months” — Checks to delete old files at most the given time frame. [http] The [http] table defines settings for HTTP behavior. This includes fetching crate dependencies and accessing remote git repositories. http.debug Type: boolean Default: false Environment: CARGO_HTTP_DEBUG If true , enables debugging of HTTP requests. The debug information can be seen by setting the CARGO_LOG=network=debug environment variable (or use network=trace for even more information). Be wary when posting logs from this output in a public location. The output may include headers with authentication tokens which you don’t want to leak! Be sure to review logs before posting them. http.proxy Type: string Default: none Environment: CARGO_HTTP_PROXY or HTTPS_PROXY or https_proxy or http_proxy Sets an HTTP and HTTPS proxy to use. The format is in libcurl format as in [protocol://]host[:port] . If not set, Cargo will also check the http.proxy setting in your global git configuration. If none of those are set, the HTTPS_PROXY or https_proxy environment variables set the proxy for HTTPS requests, and http_proxy sets it for HTTP requests. http.timeout Type: integer Default: 30 Environment: CARGO_HTTP_TIMEOUT or HTTP_TIMEOUT Sets the timeout for each HTTP request, in seconds. http.cainfo Type: string (path) Default: none Environment: CARGO_HTTP_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify TLS certificates. If not specified, Cargo attempts to use the system certificates. http.proxy-cainfo Type: string (path) Default: falls back to http.cainfo if not set Environment: CARGO_HTTP_PROXY_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify proxy TLS certificates. http.check-revoke Type: boolean Default: true (Windows) false (all others) Environment: CARGO_HTTP_CHECK_REVOKE This determines whether or not TLS certificate revocation checks should be performed. This only works on Windows. http.ssl-version Type: string or min/max table Default: none Environment: CARGO_HTTP_SSL_VERSION This sets the minimum TLS version to use. It takes a string, with one of the possible values of "default" , "tlsv1" , "tlsv1.0" , "tlsv1.1" , "tlsv1.2" , or "tlsv1.3" . This may alternatively take a table with two keys, min and max , which each take a string value of the same kind that specifies the minimum and maximum range of TLS versions to use. The default is a minimum version of "tlsv1.0" and a max of the newest version supported on your platform, typically "tlsv1.3" . http.low-speed-limit Type: integer Default: 10 Environment: CARGO_HTTP_LOW_SPEED_LIMIT This setting controls timeout behavior for slow connections. If the average transfer speed in bytes per second is below the given value for http.timeout seconds (default 30 seconds), then the connection is considered too slow and Cargo will abort and retry. http.multiplexing Type: boolean Default: true Environment: CARGO_HTTP_MULTIPLEXING When true , Cargo will attempt to use the HTTP2 protocol with multiplexing. This allows multiple requests to use the same connection, usually improving performance when fetching multiple files. If false , Cargo will use HTTP 1.1 without pipelining. http.user-agent Type: string Default: Cargo’s version Environment: CARGO_HTTP_USER_AGENT Specifies a custom user-agent header to use. The default if not specified is a string that includes Cargo’s version. [install] The [install] table defines defaults for the cargo install command. install.root Type: string (path) Default: Cargo’s home directory Environment: CARGO_INSTALL_ROOT Sets the path to the root directory for installing executables for cargo install . Executables go into a bin directory underneath the root. To track information of installed executables, some extra files, such as .crates.toml and .crates2.json , are also created under this root. The default if not specified is Cargo’s home directory (default .cargo in your home directory). Can be overridden with the --root command-line option. [net] The [net] table controls networking configuration. net.retry Type: integer Default: 3 Environment: CARGO_NET_RETRY Number of times to retry possibly spurious network errors. net.git-fetch-with-cli Type: boolean Default: false Environment: CARGO_NET_GIT_FETCH_WITH_CLI If this is true , then Cargo will use the git executable to fetch registry indexes and git dependencies. If false , then it uses a built-in git library. Setting this to true can be helpful if you have special authentication requirements that Cargo does not support. See Git Authentication for more information about setting up git authentication. net.offline Type: boolean Default: false Environment: CARGO_NET_OFFLINE If this is true , then Cargo will avoid accessing the network, and attempt to proceed with locally cached data. If false , Cargo will access the network as needed, and generate an error if it encounters a network error. Can be overridden with the --offline command-line option. net.ssh The [net.ssh] table contains settings for SSH connections. net.ssh.known-hosts Type: array of strings Default: see description Environment: not supported The known-hosts array contains a list of SSH host keys that should be accepted as valid when connecting to an SSH server (such as for SSH git dependencies). Each entry should be a string in a format similar to OpenSSH known_hosts files. Each string should start with one or more hostnames separated by commas, a space, the key type name, a space, and the base64-encoded key. For example: [net.ssh] known-hosts = [ "example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFO4Q5T0UV0SQevair9PFwoxY9dl4pQl3u5phoqJH3cF" ] Cargo will attempt to load known hosts keys from common locations supported in OpenSSH, and will join those with any listed in a Cargo configuration file. If any matching entry has the correct key, the connection will be allowed. Cargo comes with the host keys for github.com built-in. If those ever change, you can add the new keys to the config or known_hosts file. See Git Authentication for more details. [patch] Just as you can override dependencies using [patch] in Cargo.toml , you can override them in the cargo configuration file to apply those patches to any affected build. The format is identical to the one used in Cargo.toml . Since .cargo/config.toml files are not usually checked into source control, you should prefer patching using Cargo.toml where possible to ensure that other developers can compile your crate in their own environments. Patching through cargo configuration files is generally only appropriate when the patch section is automatically generated by an external build tool. If a given dependency is patched both in a cargo configuration file and a Cargo.toml file, the patch in the configuration file is used. If multiple configuration files patch the same dependency, standard cargo configuration merging is used, which prefers the value defined closest to the current directory, with $HOME/.cargo/config.toml taking the lowest precedence. Relative path dependencies in such a [patch] section are resolved relative to the configuration file they appear in. [profile] The [profile] table can be used to globally change profile settings, and override settings specified in Cargo.toml . It has the same syntax and options as profiles specified in Cargo.toml . See the Profiles chapter for details about the options. [profile.<name>.build-override] Environment: CARGO_PROFILE_<name>_BUILD_OVERRIDE_<key> The build-override table overrides settings for build scripts, proc macros, and their dependencies. It has the same keys as a normal profile. See the overrides section for more details. [profile.<name>.package.<name>] Environment: not supported The package table overrides settings for specific packages. It has the same keys as a normal profile, minus the panic , lto , and rpath settings. See the overrides section for more details. profile.<name>.codegen-units Type: integer Default: See profile docs. Environment: CARGO_PROFILE_<name>_CODEGEN_UNITS See codegen-units . profile.<name>.debug Type: integer or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG See debug . profile.<name>.split-debuginfo Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_SPLIT_DEBUGINFO See split-debuginfo . profile.<name>.debug-assertions Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG_ASSERTIONS See debug-assertions . profile.<name>.incremental Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_INCREMENTAL See incremental . profile.<name>.lto Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_LTO See lto . profile.<name>.overflow-checks Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_OVERFLOW_CHECKS See overflow-checks . profile.<name>.opt-level Type: integer or string Default: See profile docs. Environment: CARGO_PROFILE_<name>_OPT_LEVEL See opt-level . profile.<name>.panic Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_PANIC See panic . profile.<name>.rpath Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_RPATH See rpath . profile.<name>.strip Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_STRIP See strip . [resolver] The [resolver] table overrides dependency resolution behavior for local development (e.g. excludes cargo install ). resolver.incompatible-rust-versions Type: string Default: See resolver docs Environment: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS When resolving which version of a dependency to use, select how versions with incompatible package.rust-version s are treated. Values include: allow : treat rust-version -incompatible versions like any other version fallback : only consider rust-version -incompatible versions if no other version matched Can be overridden with --ignore-rust-version CLI option Setting the dependency’s version requirement higher than any version with a compatible rust-version Specifying the version to cargo update with --precise See the resolver chapter for more details. MSRV: allow is supported on any version fallback is respected as of 1.84 [registries] The [registries] table is used for specifying additional registries . It consists of a sub-table for each named registry. registries.<name>.index Type: string (url) Default: none Environment: CARGO_REGISTRIES_<name>_INDEX Specifies the URL of the index for the registry. registries.<name>.token Type: string Default: none Environment: CARGO_REGISTRIES_<name>_TOKEN Specifies the authentication token for the given registry. This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registries.<name>.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRIES_<name>_CREDENTIAL_PROVIDER Specifies the credential provider for the given registry. If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registries.crates-io.protocol Type: string Default: "sparse" Environment: CARGO_REGISTRIES_CRATES_IO_PROTOCOL Specifies the protocol used to access crates.io. Allowed values are git or sparse . git causes Cargo to clone the entire index of all packages ever published to crates.io from https://github.com/rust-lang/crates.io-index/ . This can have performance implications due to the size of the index. sparse is a newer protocol which uses HTTPS to download only what is necessary from https://index.crates.io/ . This can result in a significant performance improvement for resolving new dependencies in most situations. More information about registry protocols may be found in the Registries chapter . [registry] The [registry] table controls the default registry used when one is not specified. registry.index This value is no longer accepted and should not be used. registry.default Type: string Default: "crates-io" Environment: CARGO_REGISTRY_DEFAULT The name of the registry (from the registries table ) to use by default for registry commands like cargo publish . Can be overridden with the --registry command-line option. registry.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRY_CREDENTIAL_PROVIDER Specifies the credential provider for crates.io . If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registry.token Type: string Default: none Environment: CARGO_REGISTRY_TOKEN Specifies the authentication token for crates.io . This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registry.global-credential-providers Type: array Default: ["cargo:token"] Environment: CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS Specifies the list of global credential providers. If credential provider is not set for a specific registry using registries.<name>.credential-provider , Cargo will use the credential providers in this list. Providers toward the end of the list have precedence. Path and arguments are split on spaces. If the path or arguments contains spaces, the credential provider should be defined in the [credential-alias] table and referenced here by its alias. See Registry Authentication for more information. [source] The [source] table defines the registry sources available. See Source Replacement for more information. It consists of a sub-table for each named source. A source should only define one kind (directory, registry, local-registry, or git). source.<name>.replace-with Type: string Default: none Environment: not supported If set, replace this source with the given named source or named registry. source.<name>.directory Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a directory source. source.<name>.registry Type: string (url) Default: none Environment: not supported Sets the URL to use for a registry source. source.<name>.local-registry Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a local registry source. source.<name>.git Type: string (url) Default: none Environment: not supported Sets the URL to use for a git repository source. source.<name>.branch Type: string Default: none Environment: not supported Sets the branch name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.tag Type: string Default: none Environment: not supported Sets the tag name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.rev Type: string Default: none Environment: not supported Sets the revision to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. [target] The [target] table is used for specifying settings for specific platform targets. It consists of a sub-table which is either a platform triple or a cfg() expression . The given values will be used if the target platform matches either the <triple> value or the <cfg> expression. [target.thumbv7m-none-eabi] linker = "arm-none-eabi-gcc" runner = "my-emulator" rustflags = ["…", "…"] [target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "my-arm-wrapper" rustflags = ["…", "…"] cfg values come from those built-in to the compiler (run rustc --print=cfg to view) and extra --cfg flags passed to rustc (such as those defined in RUSTFLAGS ). Do not try to match on debug_assertions , test , Cargo features like feature="foo" , or values set by build scripts . If using a target spec JSON file, the <triple> value is the filename stem. For example --target foo/bar.json would match [target.bar] . target.<triple>.ar This option is deprecated and unused. target.<triple>.linker Type: string (program path) Default: none Environment: CARGO_TARGET_<triple>_LINKER Specifies the linker which is passed to rustc (via -C linker ) when the <triple> is being compiled for. By default, the linker is not overridden. target.<cfg>.linker This is similar to the target linker , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.runner Type: string or array of strings ( program path with args ) Default: none Environment: CARGO_TARGET_<triple>_RUNNER If a runner is provided, executables for the target <triple> will be executed by invoking the specified runner with the actual executable passed as an argument. This applies to cargo run , cargo test and cargo bench commands. By default, compiled executables are executed directly. target.<cfg>.runner This is similar to the target runner , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.rustflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustflags for more details on the different ways to specific extra flags. target.<cfg>.rustflags This is similar to the target rustflags , but using a cfg() expression . If several <cfg> and <triple> entries match the current target, the flags are joined together. target.<triple>.rustdocflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTDOCFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustdocflags for more details on the different ways to specific extra flags. target.<triple>.<links> The links sub-table provides a way to override a build script . When specified, the build script for the given links library will not be run, and the given values will be used instead. [target.x86_64-unknown-linux-gnu.foo] rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] The [term] table controls terminal output and interaction. term.quiet Type: boolean Default: false Environment: CARGO_TERM_QUIET Controls whether or not log messages are displayed by Cargo. Specifying the --quiet flag will override and force quiet output. Specifying the --verbose flag will override and disable quiet output. term.verbose Type: boolean Default: false Environment: CARGO_TERM_VERBOSE Controls whether or not extra detailed messages are displayed by Cargo. Specifying the --quiet flag will override and disable verbose output. Specifying the --verbose flag will override and force verbose output. term.color Type: string Default: "auto" Environment: CARGO_TERM_COLOR Controls whether or not colored output is used in the terminal. Possible values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. Can be overridden with the --color command-line option. term.hyperlinks Type: bool Default: auto-detect Environment: CARGO_TERM_HYPERLINKS Controls whether or not hyperlinks are used in the terminal. term.unicode Type: bool Default: auto-detect Environment: CARGO_TERM_UNICODE Control whether output can be rendered using non-ASCII unicode characters. term.progress.when Type: string Default: "auto" Environment: CARGO_TERM_PROGRESS_WHEN Controls whether or not progress bar is shown in the terminal. Possible values: auto (default): Intelligently guess whether to show progress bar. always : Always show progress bar. never : Never show progress bar. term.progress.width Type: integer Default: none Environment: CARGO_TERM_PROGRESS_WIDTH Sets the width for progress bar. term.progress.term-integration Type: bool Default: auto-detect Environment: CARGO_TERM_PROGRESS_TERM_INTEGRATION Report progress to the terminal emulator for display in places like the task bar. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/items/external-blocks.html | External blocks - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [items .extern] External blocks [items .extern .syntax] Syntax ExternBlock → unsafe ? 1 extern Abi ? { InnerAttribute * ExternalItem * } ExternalItem → OuterAttribute * ( MacroInvocationSemi | Visibility ? StaticItem | Visibility ? Function ) Show Railroad ExternBlock unsafe extern Abi { InnerAttribute ExternalItem } ExternalItem OuterAttribute MacroInvocationSemi Visibility StaticItem Visibility Function [items .extern .intro] External blocks provide declarations of items that are not defined in the current crate and are the basis of Rust’s foreign function interface. These are akin to unchecked imports. [items .extern .allowed-kinds] Two kinds of item declarations are allowed in external blocks: functions and statics . [items .extern .safety] Calling unsafe functions or accessing unsafe statics that are declared in external blocks is only allowed in an unsafe context . [items .extern .namespace] The external block defines its functions and statics in the value namespace of the module or block where it is located. [items .extern .unsafe-required] The unsafe keyword is semantically required to appear before the extern keyword on external blocks. [items .extern .edition2024] 2024 Edition differences Prior to the 2024 edition, the unsafe keyword is optional. The safe and unsafe item qualifiers are only allowed if the external block itself is marked as unsafe . [items .extern .fn] Functions [items .extern .fn .body] Functions within external blocks are declared in the same way as other Rust functions, with the exception that they must not have a body and are instead terminated by a semicolon. [items .extern .fn .param-patterns] Patterns are not allowed in parameters, only IDENTIFIER or _ may be used. [items .extern .fn .qualifiers] The safe and unsafe function qualifiers are allowed, but other function qualifiers (e.g. const , async , extern ) are not. [items .extern .fn .foreign-abi] Functions within external blocks may be called by Rust code, just like functions defined in Rust. The Rust compiler automatically translates between the Rust ABI and the foreign ABI. [items .extern .fn .safety] A function declared in an extern block is implicitly unsafe unless the safe function qualifier is present. [items .extern .fn .fn-ptr] When coerced to a function pointer, a function declared in an extern block has type extern "abi" for<'l1, ..., 'lm> fn(A1, ..., An) -> R , where 'l1 , … 'lm are its lifetime parameters, A1 , …, An are the declared types of its parameters, R is the declared return type. [items .extern .static] Statics [items .extern .static .intro] Statics within external blocks are declared in the same way as statics outside of external blocks, except that they do not have an expression initializing their value. [items .extern .static .safety] Unless a static item declared in an extern block is qualified as safe , it is unsafe to access that item, whether or not it’s mutable, because there is nothing guaranteeing that the bit pattern at the static’s memory is valid for the type it is declared with, since some arbitrary (e.g. C) code is in charge of initializing the static. [items .extern .static .mut] Extern statics can be either immutable or mutable just like statics outside of external blocks. [items .extern .static .read-only] An immutable static must be initialized before any Rust code is executed. It is not enough for the static to be initialized before Rust code reads from it. Once Rust code runs, mutating an immutable static (from inside or outside Rust) is UB, except if the mutation happens to bytes inside of an UnsafeCell . [items .extern .abi] ABI [items .extern .abi .intro] The extern keyword can be followed by an optional ABI string. The ABI specifies the calling convention of the functions in the block. The calling convention defines a low-level interface for functions, such as how arguments are placed in registers or on the stack, how return values are passed, and who is responsible for cleaning up the stack. Example #![allow(unused)] fn main() { // Interface to the Windows API. unsafe extern "system" { /* ... */ } } [items .extern .abi .default] If the ABI string is not specified, it defaults to "C" . Note The extern syntax without an explicit ABI is being phased out, so it’s better to always write the ABI explicitly. For more details, see Rust issue #134986 . [items .extern .abi .standard] The following ABI strings are supported on all platforms: [items .extern .abi .rust] unsafe extern "Rust" — The native calling convention for Rust functions and closures. This is the default when a function is declared without using extern fn . The Rust ABI offers no stability guarantees. [items .extern .abi .c] unsafe extern "C" — The “C” ABI matches the default ABI chosen by the dominant C compiler for the target. [items .extern .abi .system] unsafe extern "system" — This is equivalent to extern "C" except on Windows x86_32 where it is equivalent to "stdcall" . Note As the correct underlying ABI on Windows is target-specific, it’s best to use extern "system" when attempting to link Windows API functions that don’t use an explicitly defined ABI. [items .extern .abi .unwind] extern "C-unwind" and extern "system-unwind" — Identical to "C" and "system" , respectively, but with different behavior when the callee unwinds (by panicking or throwing a C++ style exception). [items .extern .abi .platform] There are also some platform-specific ABI strings: [items .extern .abi .cdecl] unsafe extern "cdecl" — The calling convention typically used with x86_32 C code. Only available on x86_32 targets. Corresponds to MSVC’s __cdecl and GCC and clang’s __attribute__((cdecl)) . Note For details, see: https://learn.microsoft.com/en-us/cpp/cpp/cdecl https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl [items .extern .abi .stdcall] unsafe extern "stdcall" — The calling convention typically used by the Win32 API on x86_32. Only available on x86_32 targets. Corresponds to MSVC’s __stdcall and GCC and clang’s __attribute__((stdcall)) . Note For details, see: https://learn.microsoft.com/en-us/cpp/cpp/stdcall https://en.wikipedia.org/wiki/X86_calling_conventions#stdcall [items .extern .abi .win64] unsafe extern "win64" — The Windows x64 ABI. Only available on x86_64 targets. “win64” is the same as the “C” ABI on Windows x86_64 targets. Corresponds to GCC and clang’s __attribute__((ms_abi)) . Note For details, see: https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_x64_calling_convention [items .extern .abi .sysv64] unsafe extern "sysv64" — The System V ABI. Only available on x86_64 targets. “sysv64” is the same as the “C” ABI on non-Windows x86_64 targets. Corresponds to GCC and clang’s __attribute__((sysv_abi)) . Note For details, see: https://wiki.osdev.org/System_V_ABI https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI [items .extern .abi .aapcs] unsafe extern "aapcs" — The soft-float ABI for ARM. Only available on ARM32 targets. “aapcs” is the same as the “C” ABI on soft-float ARM32. Corresponds to clang’s __attribute__((pcs("aapcs"))) . Note For details, see: Arm Procedure Call Standard [items .extern .abi .fastcall] unsafe extern "fastcall" — A “fast” variant of stdcall that passes some arguments in registers. Only available on x86_32 targets. Corresponds to MSVC’s __fastcall and GCC and clang’s __attribute__((fastcall)) . Note For details, see: https://learn.microsoft.com/en-us/cpp/cpp/fastcall https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall [items .extern .abi .thiscall] unsafe extern "thiscall" — The calling convention typically used on C++ class member functions on x86_32 MSVC. Only available on x86_32 targets. Corresponds to MSVC’s __thiscall and GCC and clang’s __attribute__((thiscall)) . Note For details, see: https://en.wikipedia.org/wiki/X86_calling_conventions#thiscall https://learn.microsoft.com/en-us/cpp/cpp/thiscall [items .extern .abi .efiapi] unsafe extern "efiapi" — The ABI used for UEFI functions. Only available on x86 and ARM targets (32bit and 64bit). [items .extern .abi .platform-unwind-variants] Like "C" and "system" , most platform-specific ABI strings also have a corresponding -unwind variant ; specifically, these are: "aapcs-unwind" "cdecl-unwind" "fastcall-unwind" "stdcall-unwind" "sysv64-unwind" "thiscall-unwind" "win64-unwind" [items .extern .variadic] Variadic functions Functions within external blocks may be variadic by specifying ... as the last argument. The variadic parameter may optionally be specified with an identifier. #![allow(unused)] fn main() { unsafe extern "C" { unsafe fn foo(...); unsafe fn bar(x: i32, ...); unsafe fn with_name(format: *const u8, args: ...); // SAFETY: This function guarantees it will not access // variadic arguments. safe fn ignores_variadic_arguments(x: i32, ...); } } Warning The safe qualifier should not be used on a function in an extern block unless that function guarantees that it will not access the variadic arguments at all. Passing an unexpected number of arguments or arguments of unexpected type to a variadic function may lead to undefined behavior . [items .extern .variadic .conventions] Variadic parameters can only be specified within extern blocks with the following ABI strings or their corresponding -unwind variants : "aapcs" "C" "cdecl" "efiapi" "sysv64" "win64" [items .extern .attributes] Attributes on extern blocks [items .extern .attributes .intro] The following attributes control the behavior of external blocks. [items .extern .attributes .link] The link attribute [items .extern .attributes .link .intro] The link attribute specifies the name of a native library that the compiler should link with for the items within an extern block. [items .extern .attributes .link .syntax] It uses the MetaListNameValueStr syntax to specify its inputs. The name key is the name of the native library to link. The kind key is an optional value which specifies the kind of library with the following possible values: [items .extern .attributes .link .dylib] dylib — Indicates a dynamic library. This is the default if kind is not specified. [items .extern .attributes .link .static] static — Indicates a static library. [items .extern .attributes .link .framework] framework — Indicates a macOS framework. This is only valid for macOS targets. [items .extern .attributes .link .raw-dylib] raw-dylib — Indicates a dynamic library where the compiler will generate an import library to link against (see dylib versus raw-dylib below for details). This is only valid for Windows targets. [items .extern .attributes .link .name-requirement] The name key must be included if kind is specified. [items .extern .attributes .link .modifiers] The optional modifiers argument is a way to specify linking modifiers for the library to link. [items .extern .attributes .link .modifiers .syntax] Modifiers are specified as a comma-delimited string with each modifier prefixed with either a + or - to indicate that the modifier is enabled or disabled, respectively. [items .extern .attributes .link .modifiers .multiple] Specifying multiple modifiers arguments in a single link attribute, or multiple identical modifiers in the same modifiers argument is not currently supported. Example: #[link(name = "mylib", kind = "static", modifiers = "+whole-archive")] . [items .extern .attributes .link .wasm_import_module] The wasm_import_module key may be used to specify the WebAssembly module name for the items within an extern block when importing symbols from the host environment. The default module name is env if wasm_import_module is not specified. #[link(name = "crypto")] unsafe extern { // … } #[link(name = "CoreFoundation", kind = "framework")] unsafe extern { // … } #[link(wasm_import_module = "foo")] unsafe extern { // … } [items .extern .attributes .link .empty-block] It is valid to add the link attribute on an empty extern block. You can use this to satisfy the linking requirements of extern blocks elsewhere in your code (including upstream crates) instead of adding the attribute to each extern block. [items .extern .attributes .link .modifiers .bundle] Linking modifiers: bundle [items .extern .attributes .link .modifiers .bundle .allowed-kinds] This modifier is only compatible with the static linking kind. Using any other kind will result in a compiler error. [items .extern .attributes .link .modifiers .bundle .behavior] When building a rlib or staticlib +bundle means that the native static library will be packed into the rlib or staticlib archive, and then retrieved from there during linking of the final binary. [items .extern .attributes .link .modifiers .bundle .behavior-negative] When building a rlib -bundle means that the native static library is registered as a dependency of that rlib “by name”, and object files from it are included only during linking of the final binary, the file search by that name is also performed during final linking. When building a staticlib -bundle means that the native static library is simply not included into the archive and some higher level build system will need to add it later during linking of the final binary. [items .extern .attributes .link .modifiers .bundle .no-effect] This modifier has no effect when building other targets like executables or dynamic libraries. [items .extern .attributes .link .modifiers .bundle .default] The default for this modifier is +bundle . More implementation details about this modifier can be found in bundle documentation for rustc . [items .extern .attributes .link .modifiers .whole-archive] Linking modifiers: whole-archive [items .extern .attributes .link .modifiers .whole-archive .allowed-kinds] This modifier is only compatible with the static linking kind. Using any other kind will result in a compiler error. [items .extern .attributes .link .modifiers .whole-archive .behavior] +whole-archive means that the static library is linked as a whole archive without throwing any object files away. [items .extern .attributes .link .modifiers .whole-archive .default] The default for this modifier is -whole-archive . More implementation details about this modifier can be found in whole-archive documentation for rustc . [items .extern .attributes .link .modifiers .verbatim] Linking modifiers: verbatim [items .extern .attributes .link .modifiers .verbatim .allowed-kinds] This modifier is compatible with all linking kinds. [items .extern .attributes .link .modifiers .verbatim .behavior] +verbatim means that rustc itself won’t add any target-specified library prefixes or suffixes (like lib or .a ) to the library name, and will try its best to ask for the same thing from the linker. [items .extern .attributes .link .modifiers .verbatim .behavior-negative] -verbatim means that rustc will either add a target-specific prefix and suffix to the library name before passing it to linker, or won’t prevent linker from implicitly adding it. [items .extern .attributes .link .modifiers .verbatim .default] The default for this modifier is -verbatim . More implementation details about this modifier can be found in verbatim documentation for rustc . [items .extern .attributes .link .kind-raw-dylib] dylib versus raw-dylib [items .extern .attributes .link .kind-raw-dylib .intro] On Windows, linking against a dynamic library requires that an import library is provided to the linker: this is a special static library that declares all of the symbols exported by the dynamic library in such a way that the linker knows that they have to be dynamically loaded at runtime. [items .extern .attributes .link .kind-raw-dylib .import] Specifying kind = "dylib" instructs the Rust compiler to link an import library based on the name key. The linker will then use its normal library resolution logic to find that import library. Alternatively, specifying kind = "raw-dylib" instructs the compiler to generate an import library during compilation and provide that to the linker instead. [items .extern .attributes .link .kind-raw-dylib .platform-specific] raw-dylib is only supported on Windows. Using it when targeting other platforms will result in a compiler error. [items .extern .attributes .link .import_name_type] The import_name_type key [items .extern .attributes .link .import_name_type .intro] On x86 Windows, names of functions are “decorated” (i.e., have a specific prefix and/or suffix added) to indicate their calling convention. For example, a stdcall calling convention function with the name fn1 that has no arguments would be decorated as _fn1@0 . However, the PE Format does also permit names to have no prefix or be undecorated. Additionally, the MSVC and GNU toolchains use different decorations for the same calling conventions which means, by default, some Win32 functions cannot be called using the raw-dylib link kind via the GNU toolchain. [items .extern .attributes .link .import_name_type .values] To allow for these differences, when using the raw-dylib link kind you may also specify the import_name_type key with one of the following values to change how functions are named in the generated import library: decorated : The function name will be fully-decorated using the MSVC toolchain format. noprefix : The function name will be decorated using the MSVC toolchain format, but skipping the leading ? , @ , or optionally _ . undecorated : The function name will not be decorated. [items .extern .attributes .link .import_name_type .default] If the import_name_type key is not specified, then the function name will be fully-decorated using the target toolchain’s format. [items .extern .attributes .link .import_name_type .variables] Variables are never decorated and so the import_name_type key has no effect on how they are named in the generated import library. [items .extern .attributes .link .import_name_type .platform-specific] The import_name_type key is only supported on x86 Windows. Using it when targeting other platforms will result in a compiler error. [items .extern .attributes .link_name] The link_name attribute [items .extern .attributes .link_name .intro] The link_name attribute may be applied to declarations inside an extern block to specify the symbol to import for the given function or static. Example #![allow(unused)] fn main() { unsafe extern "C" { #[link_name = "actual_symbol_name"] safe fn name_in_rust(); } } [items .extern .attributes .link_name .syntax] The link_name attribute uses the MetaNameValueStr syntax. [items .extern .attributes .link_name .allowed-positions] The link_name attribute may only be applied to a function or static item in an extern block. Note rustc ignores use in other positions but lints against it. This may become an error in the future. [items .extern .attributes .link_name .duplicates] Only the last use of link_name on an item has effect. Note rustc lints against any use preceding the last. This may become an error in the future. [items .extern .attributes .link_name .link_ordinal] The link_name attribute may not be used with the link_ordinal attribute. [items .extern .attributes .link_ordinal] The link_ordinal attribute [items .extern .attributes .link_ordinal .intro] The link_ordinal attribute can be applied on declarations inside an extern block to indicate the numeric ordinal to use when generating the import library to link against. An ordinal is a unique number per symbol exported by a dynamic library on Windows and can be used when the library is being loaded to find that symbol rather than having to look it up by name. Warning link_ordinal should only be used in cases where the ordinal of the symbol is known to be stable: if the ordinal of a symbol is not explicitly set when its containing binary is built then one will be automatically assigned to it, and that assigned ordinal may change between builds of the binary. #![allow(unused)] fn main() { #[cfg(all(windows, target_arch = "x86"))] #[link(name = "exporter", kind = "raw-dylib")] unsafe extern "stdcall" { #[link_ordinal(15)] safe fn imported_function_stdcall(i: i32); } } [items .extern .attributes .link_ordinal .allowed-kinds] This attribute is only used with the raw-dylib linking kind. Using any other kind will result in a compiler error. [items .extern .attributes .link_ordinal .exclusive] Using this attribute with the link_name attribute will result in a compiler error. [items .extern .attributes .fn-parameters] Attributes on function parameters Attributes on extern function parameters follow the same rules and restrictions as regular function parameters . Starting with the 2024 Edition, the unsafe keyword is required semantically. ↩ | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/rustc/command-line-arguments.html#option-cfg | Command-line Arguments - The rustc book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The rustc book Command-line Arguments Here's a list of command-line arguments to rustc and what they do. -h / --help : get help This flag will print out help information for rustc . --cfg : configure the compilation environment This flag can turn on or off various #[cfg] settings for conditional compilation . The value can either be a single identifier or two identifiers separated by = . For examples, --cfg 'verbose' or --cfg 'feature="serde"' . These correspond to #[cfg(verbose)] and #[cfg(feature = "serde")] respectively. --check-cfg : configure compile-time checking of conditional compilation This flag enables checking conditional configurations of the crate at compile-time, specifically it helps configure the set of expected cfg names and values, in order to check that every reachable #[cfg] matches the expected config names and values. This is different from the --cfg flag above which activates some config but do not expect them. This is useful to prevent stalled conditions, typos, ... Refer to the Checking conditional configurations of this book for further details and explanation. For examples, --check-cfg 'cfg(verbose)' or --check-cfg 'cfg(feature, values("serde"))' . These correspond to #[cfg(verbose)] and #[cfg(feature = "serde")] respectively. -L : add a directory to the library search path The -L flag adds a path to search for external crates and libraries. The kind of search path can optionally be specified with the form -L KIND=PATH where KIND may be one of: dependency — Only search for transitive dependencies in this directory. crate — Only search for this crate's direct dependencies in this directory. native — Only search for native libraries in this directory. framework — Only search for macOS frameworks in this directory. all — Search for all library kinds in this directory, except frameworks. This is the default if KIND is not specified. -l : link the generated crate to a native library Syntax: -l [KIND[:MODIFIERS]=]NAME[:RENAME] . This flag allows you to specify linking to a specific native library when building a crate. The kind of library can optionally be specified with the form -l KIND=lib where KIND may be one of: dylib — A native dynamic library. static — A native static library (such as a .a archive). framework — A macOS framework. If the kind is specified, then linking modifiers can be attached to it. Modifiers are specified as a comma-delimited string with each modifier prefixed with either a + or - to indicate that the modifier is enabled or disabled, respectively. Specifying multiple modifiers arguments in a single link attribute, or multiple identical modifiers in the same modifiers argument is not currently supported. Example: -l static:+whole-archive=mylib . The kind of library and the modifiers can also be specified in a #[link] attribute . If the kind is not specified in the link attribute or on the command-line, it will link a dynamic library by default, except when building a static executable. If the kind is specified on the command-line, it will override the kind specified in a link attribute. The name used in a link attribute may be overridden using the form -l ATTR_NAME:LINK_NAME where ATTR_NAME is the name in the link attribute, and LINK_NAME is the name of the actual library that will be linked. Linking modifiers: whole-archive This modifier is only compatible with the static linking kind. Using any other kind will result in a compiler error. +whole-archive means that the static library is linked as a whole archive without throwing any object files away. This modifier translates to --whole-archive for ld -like linkers, to /WHOLEARCHIVE for link.exe , and to -force_load for ld64 . The modifier does nothing for linkers that don't support it. The default for this modifier is -whole-archive . Linking modifiers: bundle This modifier is only compatible with the static linking kind. Using any other kind will result in a compiler error. When building a rlib or staticlib +bundle means that the native static library will be packed into the rlib or staticlib archive, and then retrieved from there during linking of the final binary. When building a rlib -bundle means that the native static library is registered as a dependency of that rlib "by name", and object files from it are included only during linking of the final binary, the file search by that name is also performed during final linking. When building a staticlib -bundle means that the native static library is simply not included into the archive and some higher level build system will need to add it later during linking of the final binary. This modifier has no effect when building other targets like executables or dynamic libraries. The default for this modifier is +bundle . Linking modifiers: verbatim This modifier is compatible with all linking kinds. +verbatim means that rustc itself won't add any target-specified library prefixes or suffixes (like lib or .a ) to the library name, and will try its best to ask for the same thing from the linker. For ld -like linkers supporting GNU extensions rustc will use the -l:filename syntax (note the colon) when passing the library, so the linker won't add any prefixes or suffixes to it. See -l namespec in ld documentation for more details. For linkers not supporting any verbatim modifiers (e.g. link.exe or ld64 ) the library name will be passed as is. So the most reliable cross-platform use scenarios for this option are when no linker is involved, for example bundling native libraries into rlibs. -verbatim means that rustc will either add a target-specific prefix and suffix to the library name before passing it to linker, or won't prevent linker from implicitly adding it. In case of raw-dylib kind in particular .dll will be added to the library name on Windows. The default for this modifier is -verbatim . NOTE: Even with +verbatim and -l:filename syntax ld -like linkers do not typically support passing absolute paths to libraries. Usually such paths need to be passed as input files without using any options like -l , e.g. ld /my/absolute/path . -Clink-arg=/my/absolute/path can be used for doing this from stable rustc . --crate-type : a list of types of crates for the compiler to emit This instructs rustc on which crate type to build. This flag accepts a comma-separated list of values, and may be specified multiple times. The valid crate types are: lib — Generates a library kind preferred by the compiler, currently defaults to rlib . rlib — A Rust static library. staticlib — A native static library. dylib — A Rust dynamic library. cdylib — A native dynamic library. bin — A runnable executable program. proc-macro — Generates a format suitable for a procedural macro library that may be loaded by the compiler. The crate type may be specified with the crate_type attribute . The --crate-type command-line value will override the crate_type attribute. More details may be found in the linkage chapter of the reference. --crate-name : specify the name of the crate being built This informs rustc of the name of your crate. --edition : specify the edition to use This flag takes a value of 2015 , 2018 , 2021 , or 2024 . The default is 2015 . More information about editions may be found in the edition guide . --emit : specifies the types of output files to generate This flag controls the types of output files generated by the compiler. It accepts a comma-separated list of values, and may be specified multiple times. The valid emit kinds are: asm — Generates a file with the crate's assembly code. The default output filename is CRATE_NAME.s . dep-info — Generates a file with Makefile syntax that indicates all the source files that were loaded to generate the crate. The default output filename is CRATE_NAME.d . link — Generates the crates specified by --crate-type . The default output filenames depend on the crate type and platform. This is the default if --emit is not specified. llvm-bc — Generates a binary file containing the LLVM bitcode . The default output filename is CRATE_NAME.bc . llvm-ir — Generates a file containing LLVM IR . The default output filename is CRATE_NAME.ll . metadata — Generates a file containing metadata about the crate. The default output filename is libCRATE_NAME.rmeta . mir — Generates a file containing rustc's mid-level intermediate representation. The default output filename is CRATE_NAME.mir . obj — Generates a native object file. The default output filename is CRATE_NAME.o . The output filename can be set with the -o flag . A suffix may be added to the filename with the -C extra-filename flag . Output files are written to the current directory unless the --out-dir flag is used. Custom paths for individual emit kinds Each emit type can optionally be followed by = to specify an explicit output path that only applies to the output of that type. For example: --emit=link,dep-info=/path/to/dep-info.d Emit the crate itself as normal, and also emit dependency info to the specified path. --emit=llvm-ir=-,mir Emit MIR to the default filename (based on crate name), and emit LLVM IR to stdout. Emitting to stdout When using --emit or -o , output can be sent to stdout by specifying - as the path (e.g. -o - ). Binary output types can only be written to stdout if it is not a tty. Text output types ( asm , dep-info , llvm-ir and mir ) can be written to stdout regardless of whether it is a tty or not. Only one type of output can be written to stdout. Attempting to write multiple types to stdout at the same time will result in an error. --print : print compiler information This flag will allow you to set print options . -g : include debug information A synonym for -C debuginfo=2 . -O : optimize your code A synonym for -C opt-level=3 . -o : filename of the output This flag controls the output filename. --out-dir : directory to write the output in The outputted crate will be written to this directory. This flag is ignored if the -o flag is used. --explain : provide a detailed explanation of an error message Each error of rustc 's comes with an error code; this will print out a longer explanation of a given error. --test : build a test harness When compiling this crate, rustc will ignore your main function and instead produce a test harness. See the Tests chapter for more information about tests. --target : select a target triple to build This controls which target to produce. -W : set lint warnings This flag will set which lints should be set to the warn level . Note: The order of these lint level arguments is taken into account, see lint level via compiler flag for more information. --force-warn : force a lint to warn This flag sets the given lint to the forced warn level and the level cannot be overridden, even ignoring the lint caps . -A : set lint allowed This flag will set which lints should be set to the allow level . Note: The order of these lint level arguments is taken into account, see lint level via compiler flag for more information. -D : set lint denied This flag will set which lints should be set to the deny level . Note: The order of these lint level arguments is taken into account, see lint level via compiler flag for more information. -F : set lint forbidden This flag will set which lints should be set to the forbid level . Note: The order of these lint level arguments is taken into account, see lint level via compiler flag for more information. -Z : set unstable options This flag will allow you to set unstable options of rustc. In order to set multiple options, the -Z flag can be used multiple times. For example: rustc -Z verbose-internals -Z time-passes . Specifying options with -Z is only available on nightly. To view all available options run: rustc -Z help , or see The Unstable Book . --cap-lints : set the most restrictive lint level This flag lets you 'cap' lints, for more, see here . -C / --codegen : code generation options This flag will allow you to set codegen options . -V / --version : print a version This flag will print out rustc 's version. -v / --verbose : use verbose output This flag, when combined with other flags, makes them produce extra output. --extern : specify where an external library is located This flag allows you to pass the name and location for an external crate of a direct dependency. Indirect dependencies (dependencies of dependencies) are located using the -L flag . The given crate name is added to the extern prelude , similar to specifying extern crate within the root module. The given crate name does not need to match the name the library was built with. Specifying --extern has one behavior difference from extern crate : --extern merely makes the crate a candidate for being linked; it does not actually link it unless it's actively used. In rare occasions you may wish to ensure a crate is linked even if you don't actively use it from your code: for example, if it changes the global allocator or if it contains #[no_mangle] symbols for use by other programming languages. In such cases you'll need to use extern crate . This flag may be specified multiple times. This flag takes an argument with either of the following formats: CRATENAME=PATH — Indicates the given crate is found at the given path. CRATENAME — Indicates the given crate may be found in the search path, such as within the sysroot or via the -L flag. The same crate name may be specified multiple times for different crate types. If both an rlib and dylib are found, an internal algorithm is used to decide which to use for linking. The -C prefer-dynamic flag may be used to influence which is used. If the same crate name is specified with and without a path, the one with the path is used and the pathless flag has no effect. --sysroot : Override the system root The "sysroot" is where rustc looks for the crates that come with the Rust distribution; this flag allows that to be overridden. --error-format : control how errors are produced This flag lets you control the format of messages. Messages are printed to stderr. The valid options are: human — Human-readable output. This is the default. json — Structured JSON output. See the JSON chapter for more detail. short — Short, one-line messages. --color : configure coloring of output This flag lets you control color settings of the output. The valid options are: auto — Use colors if output goes to a tty. This is the default. always — Always use colors. never — Never colorize output. --diagnostic-width : specify the terminal width for diagnostics This flag takes a number that specifies the width of the terminal in characters. Formatting of diagnostics will take the width into consideration to make them better fit on the screen. --remap-path-prefix : remap source paths in output Remap source path prefixes in all output, including compiler diagnostics, debug information, macro expansions, etc. It takes a value of the form FROM=TO where a path prefix equal to FROM is rewritten to the value TO . This flag may be specified multiple times. Refer to the Remap source paths section of this book for further details and explanation. --json : configure json messages printed by the compiler When the --error-format=json option is passed to rustc then all of the compiler's diagnostic output will be emitted in the form of JSON blobs. The --json argument can be used in conjunction with --error-format=json to configure what the JSON blobs contain as well as which ones are emitted. With --error-format=json the compiler will always emit any compiler errors as a JSON blob, but the following options are also available to the --json flag to customize the output: diagnostic-short - json blobs for diagnostic messages should use the "short" rendering instead of the normal "human" default. This means that the output of --error-format=short will be embedded into the JSON diagnostics instead of the default --error-format=human . diagnostic-rendered-ansi - by default JSON blobs in their rendered field will contain a plain text rendering of the diagnostic. This option instead indicates that the diagnostic should have embedded ANSI color codes intended to be used to colorize the message in the manner rustc typically already does for terminal outputs. Note that this is usefully combined with crates like fwdansi to translate these ANSI codes on Windows to console commands or strip-ansi-escapes if you'd like to optionally remove the ansi colors afterwards. artifacts - this instructs rustc to emit a JSON blob for each artifact that is emitted. An artifact corresponds to a request from the --emit CLI argument , and as soon as the artifact is available on the filesystem a notification will be emitted. future-incompat - includes a JSON message that contains a report if the crate contains any code that may fail to compile in the future. timings - output a JSON message when a certain compilation "section" (such as frontend analysis, code generation, linking) begins or ends. Note that it is invalid to combine the --json argument with the --color argument, and it is required to combine --json with --error-format=json . See the JSON chapter for more detail. @path : load command-line flags from a path If you specify @path on the command-line, then it will open path and read command line options from it. These options are one per line; a blank line indicates an empty option. The file can use Unix or Windows style line endings, and must be encoded as UTF-8. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#environment | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#common-options | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---quiet | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://ja-jp.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1v_OJQfV5Zcu-cblOHFXfPicMkZBPGWKUMR8y2VtHCkhFimX0DXmuO_lS7lSOvuxvJGvNENLC3hXctnK0aEhIreuGRGjRkAY5nzNTCCWlumoLGOzuQm7GYuIQhI_WWXvHN-cB9_Akw-iZt | Facebook Facebook メールアドレスまたは電話番号 パスワード アカウントを忘れた場合 新しいアカウントを作成 機能の一時停止 機能の一時停止 この機能の使用ペースが早過ぎるため、機能の使用が一時的にブロックされました。 Back 日本語 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) Português (Brasil) Français (France) Deutsch アカウント登録 ログイン Messenger Facebook Lite 動画 Meta Pay Metaストア Meta Quest Ray-Ban Meta Meta AI Meta AIのコンテンツをもっと見る Instagram Threads 投票情報センター プライバシーポリシー プライバシーセンター Facebookについて 広告を作成 ページを作成 開発者 採用情報 Cookie AdChoices 規約 ヘルプ 連絡先のアップロードと非ユーザー 設定 アクティビティログ Meta © 2026 | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/std/net/enum.IpAddr.html | IpAddr in std::net - Rust This old browser is unsupported and will most likely display funky things. IpAddr std 1.92.0 (ded5c06cf 2025-12-08) IpAddr Sections Examples Variants V4 V6 Methods as_octets is_benchmarking is_documentation is_global is_ipv4 is_ipv6 is_loopback is_multicast is_unspecified parse_ascii to_canonical Trait Implementations Clone Copy Debug Display Eq From<Ipv4Addr> From<Ipv6Addr> From<[u8; 4]> From<[u8; 16]> From<[u16; 8]> FromStr Hash Ord PartialEq PartialEq<IpAddr> PartialEq<IpAddr> PartialEq<Ipv4Addr> PartialEq<Ipv6Addr> PartialOrd PartialOrd<IpAddr> PartialOrd<IpAddr> PartialOrd<Ipv4Addr> PartialOrd<Ipv6Addr> StructuralPartialEq Auto Trait Implementations Freeze RefUnwindSafe Send Sync Unpin UnwindSafe Blanket Implementations Any Borrow<T> BorrowMut<T> CloneToUninit From<T> Into<U> ToOwned ToString TryFrom<U> TryInto<U> In std:: net std :: net Enum IpAddr Copy item path 1.0.0 · Source pub enum IpAddr { V4( Ipv4Addr ), V6( Ipv6Addr ), } Expand description An IP address, either IPv4 or IPv6. This enum can contain either an Ipv4Addr or an Ipv6Addr , see their respective documentation for more details. § Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; let localhost_v4 = IpAddr::V4(Ipv4Addr::new( 127 , 0 , 0 , 1 )); let localhost_v6 = IpAddr::V6(Ipv6Addr::new( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 )); assert_eq! ( "127.0.0.1" .parse(), Ok (localhost_v4)); assert_eq! ( "::1" .parse(), Ok (localhost_v6)); assert_eq! (localhost_v4.is_ipv6(), false ); assert_eq! (localhost_v4.is_ipv4(), true ); Variants § § 1.7.0 V4( Ipv4Addr ) An IPv4 address. § 1.7.0 V6( Ipv6Addr ) An IPv6 address. Implementations § Source § impl IpAddr 1.12.0 (const: 1.50.0) · Source pub const fn is_unspecified (&self) -> bool Returns true for the special ‘unspecified’ address. See the documentation for Ipv4Addr::is_unspecified() and Ipv6Addr::is_unspecified() for more details. § Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq! (IpAddr::V4(Ipv4Addr::new( 0 , 0 , 0 , 0 )).is_unspecified(), true ); assert_eq! (IpAddr::V6(Ipv6Addr::new( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 )).is_unspecified(), true ); 1.12.0 (const: 1.50.0) · Source pub const fn is_loopback (&self) -> bool Returns true if this is a loopback address. See the documentation for Ipv4Addr::is_loopback() and Ipv6Addr::is_loopback() for more details. § Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq! (IpAddr::V4(Ipv4Addr::new( 127 , 0 , 0 , 1 )).is_loopback(), true ); assert_eq! (IpAddr::V6(Ipv6Addr::new( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0x1 )).is_loopback(), true ); Source pub const fn is_global (&self) -> bool 🔬 This is a nightly-only experimental API. ( ip #27709 ) Returns true if the address appears to be globally routable. See the documentation for Ipv4Addr::is_global() and Ipv6Addr::is_global() for more details. § Examples #![feature(ip)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq! (IpAddr::V4(Ipv4Addr::new( 80 , 9 , 12 , 3 )).is_global(), true ); assert_eq! (IpAddr::V6(Ipv6Addr::new( 0 , 0 , 0x1c9 , 0 , 0 , 0xafc8 , 0 , 0x1 )).is_global(), true ); 1.12.0 (const: 1.50.0) · Source pub const fn is_multicast (&self) -> bool Returns true if this is a multicast address. See the documentation for Ipv4Addr::is_multicast() and Ipv6Addr::is_multicast() for more details. § Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq! (IpAddr::V4(Ipv4Addr::new( 224 , 254 , 0 , 0 )).is_multicast(), true ); assert_eq! (IpAddr::V6(Ipv6Addr::new( 0xff00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 )).is_multicast(), true ); Source pub const fn is_documentation (&self) -> bool 🔬 This is a nightly-only experimental API. ( ip #27709 ) Returns true if this address is in a range designated for documentation. See the documentation for Ipv4Addr::is_documentation() and Ipv6Addr::is_documentation() for more details. § Examples #![feature(ip)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq! (IpAddr::V4(Ipv4Addr::new( 203 , 0 , 113 , 6 )).is_documentation(), true ); assert_eq! ( IpAddr::V6(Ipv6Addr::new( 0x2001 , 0xdb8 , 0 , 0 , 0 , 0 , 0 , 0 )).is_documentation(), true ); Source pub const fn is_benchmarking (&self) -> bool 🔬 This is a nightly-only experimental API. ( ip #27709 ) Returns true if this address is in a range designated for benchmarking. See the documentation for Ipv4Addr::is_benchmarking() and Ipv6Addr::is_benchmarking() for more details. § Examples #![feature(ip)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq! (IpAddr::V4(Ipv4Addr::new( 198 , 19 , 255 , 255 )).is_benchmarking(), true ); assert_eq! (IpAddr::V6(Ipv6Addr::new( 0x2001 , 0x2 , 0 , 0 , 0 , 0 , 0 , 0 )).is_benchmarking(), true ); 1.16.0 (const: 1.50.0) · Source pub const fn is_ipv4 (&self) -> bool Returns true if this address is an IPv4 address , and false otherwise. § Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq! (IpAddr::V4(Ipv4Addr::new( 203 , 0 , 113 , 6 )).is_ipv4(), true ); assert_eq! (IpAddr::V6(Ipv6Addr::new( 0x2001 , 0xdb8 , 0 , 0 , 0 , 0 , 0 , 0 )).is_ipv4(), false ); 1.16.0 (const: 1.50.0) · Source pub const fn is_ipv6 (&self) -> bool Returns true if this address is an IPv6 address , and false otherwise. § Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq! (IpAddr::V4(Ipv4Addr::new( 203 , 0 , 113 , 6 )).is_ipv6(), false ); assert_eq! (IpAddr::V6(Ipv6Addr::new( 0x2001 , 0xdb8 , 0 , 0 , 0 , 0 , 0 , 0 )).is_ipv6(), true ); 1.75.0 (const: 1.75.0) · Source pub const fn to_canonical (&self) -> IpAddr Converts this address to an IpAddr::V4 if it is an IPv4-mapped IPv6 address, otherwise returns self as-is. § Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; let localhost_v4 = Ipv4Addr::new( 127 , 0 , 0 , 1 ); assert_eq! (IpAddr::V4(localhost_v4).to_canonical(), localhost_v4); assert_eq! (IpAddr::V6(localhost_v4.to_ipv6_mapped()).to_canonical(), localhost_v4); assert_eq! (IpAddr::V4(Ipv4Addr::new( 127 , 0 , 0 , 1 )).to_canonical().is_loopback(), true ); assert_eq! (IpAddr::V6(Ipv6Addr::new( 0 , 0 , 0 , 0 , 0 , 0xffff , 0x7f00 , 0x1 )).is_loopback(), false ); assert_eq! (IpAddr::V6(Ipv6Addr::new( 0 , 0 , 0 , 0 , 0 , 0xffff , 0x7f00 , 0x1 )).to_canonical().is_loopback(), true ); Source pub const fn as_octets (&self) -> &[ u8 ] ⓘ 🔬 This is a nightly-only experimental API. ( ip_as_octets #137259 ) Returns the eight-bit integers this address consists of as a slice. § Examples #![feature(ip_as_octets)] use std::net::{Ipv4Addr, Ipv6Addr, IpAddr}; assert_eq! (IpAddr::V4(Ipv4Addr::LOCALHOST).as_octets(), & [ 127 , 0 , 0 , 1 ]); assert_eq! (IpAddr::V6(Ipv6Addr::LOCALHOST).as_octets(), & [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ]) Source § impl IpAddr Source pub fn parse_ascii (b: &[ u8 ]) -> Result < IpAddr , AddrParseError > 🔬 This is a nightly-only experimental API. ( addr_parse_ascii #101035 ) Parse an IP address from a slice of bytes. #![feature(addr_parse_ascii)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; let localhost_v4 = IpAddr::V4(Ipv4Addr::new( 127 , 0 , 0 , 1 )); let localhost_v6 = IpAddr::V6(Ipv6Addr::new( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 )); assert_eq! (IpAddr::parse_ascii( b"127.0.0.1" ), Ok (localhost_v4)); assert_eq! (IpAddr::parse_ascii( b"::1" ), Ok (localhost_v6)); Trait Implementations § 1.7.0 · Source § impl Clone for IpAddr Source § fn clone (&self) -> IpAddr Returns a duplicate of the value. Read more 1.0.0 · Source § fn clone_from (&mut self, source: &Self) Performs copy-assignment from source . Read more 1.7.0 · Source § impl Debug for IpAddr Source § fn fmt (&self, fmt: &mut Formatter <'_>) -> Result < () , Error > Formats the value using the given formatter. Read more 1.7.0 · Source § impl Display for IpAddr Source § fn fmt (&self, fmt: &mut Formatter <'_>) -> Result < () , Error > Formats the value using the given formatter. Read more 1.17.0 (const: unstable ) · Source § impl From <[ u16 ; 8 ]> for IpAddr Source § fn from (segments: [ u16 ; 8 ]) -> IpAddr Creates an IpAddr::V6 from an eight element 16-bit array. § Examples use std::net::{IpAddr, Ipv6Addr}; let addr = IpAddr::from([ 0x20du16 , 0x20cu16 , 0x20bu16 , 0x20au16 , 0x209u16 , 0x208u16 , 0x207u16 , 0x206u16 , ]); assert_eq! ( IpAddr::V6(Ipv6Addr::new( 0x20d , 0x20c , 0x20b , 0x20a , 0x209 , 0x208 , 0x207 , 0x206 , )), addr ); 1.17.0 (const: unstable ) · Source § impl From <[ u8 ; 16 ]> for IpAddr Source § fn from (octets: [ u8 ; 16 ]) -> IpAddr Creates an IpAddr::V6 from a sixteen element byte array. § Examples use std::net::{IpAddr, Ipv6Addr}; let addr = IpAddr::from([ 0x19u8 , 0x18u8 , 0x17u8 , 0x16u8 , 0x15u8 , 0x14u8 , 0x13u8 , 0x12u8 , 0x11u8 , 0x10u8 , 0x0fu8 , 0x0eu8 , 0x0du8 , 0x0cu8 , 0x0bu8 , 0x0au8 , ]); assert_eq! ( IpAddr::V6(Ipv6Addr::new( 0x1918 , 0x1716 , 0x1514 , 0x1312 , 0x1110 , 0x0f0e , 0x0d0c , 0x0b0a , )), addr ); 1.17.0 (const: unstable ) · Source § impl From <[ u8 ; 4 ]> for IpAddr Source § fn from (octets: [ u8 ; 4 ]) -> IpAddr Creates an IpAddr::V4 from a four element byte array. § Examples use std::net::{IpAddr, Ipv4Addr}; let addr = IpAddr::from([ 13u8 , 12u8 , 11u8 , 10u8 ]); assert_eq! (IpAddr::V4(Ipv4Addr::new( 13 , 12 , 11 , 10 )), addr); 1.16.0 (const: unstable ) · Source § impl From < Ipv4Addr > for IpAddr Source § fn from (ipv4: Ipv4Addr ) -> IpAddr Copies this address to a new IpAddr::V4 . § Examples use std::net::{IpAddr, Ipv4Addr}; let addr = Ipv4Addr::new( 127 , 0 , 0 , 1 ); assert_eq! ( IpAddr::V4(addr), IpAddr::from(addr) ) 1.16.0 (const: unstable ) · Source § impl From < Ipv6Addr > for IpAddr Source § fn from (ipv6: Ipv6Addr ) -> IpAddr Copies this address to a new IpAddr::V6 . § Examples use std::net::{IpAddr, Ipv6Addr}; let addr = Ipv6Addr::new( 0 , 0 , 0 , 0 , 0 , 0xffff , 0xc00a , 0x2ff ); assert_eq! ( IpAddr::V6(addr), IpAddr::from(addr) ); 1.7.0 · Source § impl FromStr for IpAddr Source § type Err = AddrParseError The associated error which can be returned from parsing. Source § fn from_str (s: & str ) -> Result < IpAddr , AddrParseError > Parses a string s to return a value of this type. Read more 1.7.0 · Source § impl Hash for IpAddr Source § fn hash <__H>(&self, state: &mut __H ) where __H: Hasher , Feeds this value into the given Hasher . Read more 1.3.0 · Source § fn hash_slice <H>(data: &[Self], state: &mut H ) where H: Hasher , Self: Sized , Feeds a slice of this type into the given Hasher . Read more 1.7.0 · Source § impl Ord for IpAddr Source § fn cmp (&self, other: & IpAddr ) -> Ordering This method returns an Ordering between self and other . Read more 1.21.0 · Source § fn max (self, other: Self) -> Self where Self: Sized , Compares and returns the maximum of two values. Read more 1.21.0 · Source § fn min (self, other: Self) -> Self where Self: Sized , Compares and returns the minimum of two values. Read more 1.50.0 · Source § fn clamp (self, min: Self, max: Self) -> Self where Self: Sized , Restrict a value to a certain interval. Read more 1.16.0 · Source § impl PartialEq < IpAddr > for Ipv4Addr Source § fn eq (&self, other: & IpAddr ) -> bool Tests for self and other values to be equal, and is used by == . 1.0.0 · Source § fn ne (&self, other: &Rhs ) -> bool Tests for != . The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.16.0 · Source § impl PartialEq < IpAddr > for Ipv6Addr Source § fn eq (&self, other: & IpAddr ) -> bool Tests for self and other values to be equal, and is used by == . 1.0.0 · Source § fn ne (&self, other: &Rhs ) -> bool Tests for != . The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.16.0 · Source § impl PartialEq < Ipv4Addr > for IpAddr Source § fn eq (&self, other: & Ipv4Addr ) -> bool Tests for self and other values to be equal, and is used by == . 1.0.0 · Source § fn ne (&self, other: &Rhs ) -> bool Tests for != . The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.16.0 · Source § impl PartialEq < Ipv6Addr > for IpAddr Source § fn eq (&self, other: & Ipv6Addr ) -> bool Tests for self and other values to be equal, and is used by == . 1.0.0 · Source § fn ne (&self, other: &Rhs ) -> bool Tests for != . The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.7.0 · Source § impl PartialEq for IpAddr Source § fn eq (&self, other: & IpAddr ) -> bool Tests for self and other values to be equal, and is used by == . 1.0.0 · Source § fn ne (&self, other: &Rhs ) -> bool Tests for != . The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.16.0 · Source § impl PartialOrd < IpAddr > for Ipv4Addr Source § fn partial_cmp (&self, other: & IpAddr ) -> Option < Ordering > This method returns an ordering between self and other values if one exists. Read more 1.0.0 · Source § fn lt (&self, other: &Rhs ) -> bool Tests less than (for self and other ) and is used by the < operator. Read more 1.0.0 · Source § fn le (&self, other: &Rhs ) -> bool Tests less than or equal to (for self and other ) and is used by the <= operator. Read more 1.0.0 · Source § fn gt (&self, other: &Rhs ) -> bool Tests greater than (for self and other ) and is used by the > operator. Read more 1.0.0 · Source § fn ge (&self, other: &Rhs ) -> bool Tests greater than or equal to (for self and other ) and is used by the >= operator. Read more 1.16.0 · Source § impl PartialOrd < IpAddr > for Ipv6Addr Source § fn partial_cmp (&self, other: & IpAddr ) -> Option < Ordering > This method returns an ordering between self and other values if one exists. Read more 1.0.0 · Source § fn lt (&self, other: &Rhs ) -> bool Tests less than (for self and other ) and is used by the < operator. Read more 1.0.0 · Source § fn le (&self, other: &Rhs ) -> bool Tests less than or equal to (for self and other ) and is used by the <= operator. Read more 1.0.0 · Source § fn gt (&self, other: &Rhs ) -> bool Tests greater than (for self and other ) and is used by the > operator. Read more 1.0.0 · Source § fn ge (&self, other: &Rhs ) -> bool Tests greater than or equal to (for self and other ) and is used by the >= operator. Read more 1.16.0 · Source § impl PartialOrd < Ipv4Addr > for IpAddr Source § fn partial_cmp (&self, other: & Ipv4Addr ) -> Option < Ordering > This method returns an ordering between self and other values if one exists. Read more 1.0.0 · Source § fn lt (&self, other: &Rhs ) -> bool Tests less than (for self and other ) and is used by the < operator. Read more 1.0.0 · Source § fn le (&self, other: &Rhs ) -> bool Tests less than or equal to (for self and other ) and is used by the <= operator. Read more 1.0.0 · Source § fn gt (&self, other: &Rhs ) -> bool Tests greater than (for self and other ) and is used by the > operator. Read more 1.0.0 · Source § fn ge (&self, other: &Rhs ) -> bool Tests greater than or equal to (for self and other ) and is used by the >= operator. Read more 1.16.0 · Source § impl PartialOrd < Ipv6Addr > for IpAddr Source § fn partial_cmp (&self, other: & Ipv6Addr ) -> Option < Ordering > This method returns an ordering between self and other values if one exists. Read more 1.0.0 · Source § fn lt (&self, other: &Rhs ) -> bool Tests less than (for self and other ) and is used by the < operator. Read more 1.0.0 · Source § fn le (&self, other: &Rhs ) -> bool Tests less than or equal to (for self and other ) and is used by the <= operator. Read more 1.0.0 · Source § fn gt (&self, other: &Rhs ) -> bool Tests greater than (for self and other ) and is used by the > operator. Read more 1.0.0 · Source § fn ge (&self, other: &Rhs ) -> bool Tests greater than or equal to (for self and other ) and is used by the >= operator. Read more 1.7.0 · Source § impl PartialOrd for IpAddr Source § fn partial_cmp (&self, other: & IpAddr ) -> Option < Ordering > This method returns an ordering between self and other values if one exists. Read more 1.0.0 · Source § fn lt (&self, other: &Rhs ) -> bool Tests less than (for self and other ) and is used by the < operator. Read more 1.0.0 · Source § fn le (&self, other: &Rhs ) -> bool Tests less than or equal to (for self and other ) and is used by the <= operator. Read more 1.0.0 · Source § fn gt (&self, other: &Rhs ) -> bool Tests greater than (for self and other ) and is used by the > operator. Read more 1.0.0 · Source § fn ge (&self, other: &Rhs ) -> bool Tests greater than or equal to (for self and other ) and is used by the >= operator. Read more 1.7.0 · Source § impl Copy for IpAddr 1.7.0 · Source § impl Eq for IpAddr 1.7.0 · Source § impl StructuralPartialEq for IpAddr Auto Trait Implementations § § impl Freeze for IpAddr § impl RefUnwindSafe for IpAddr § impl Send for IpAddr § impl Sync for IpAddr § impl Unpin for IpAddr § impl UnwindSafe for IpAddr Blanket Implementations § Source § impl<T> Any for T where T: 'static + ? Sized , Source § fn type_id (&self) -> TypeId Gets the TypeId of self . Read more Source § impl<T> Borrow <T> for T where T: ? Sized , Source § fn borrow (&self) -> &T Immutably borrows from an owned value. Read more Source § impl<T> BorrowMut <T> for T where T: ? Sized , Source § fn borrow_mut (&mut self) -> &mut T Mutably borrows from an owned value. Read more Source § impl<T> CloneToUninit for T where T: Clone , Source § unsafe fn clone_to_uninit (&self, dest: *mut u8 ) 🔬 This is a nightly-only experimental API. ( clone_to_uninit #126799 ) Performs copy-assignment from self to dest . Read more Source § impl<T> From <T> for T Source § fn from (t: T) -> T Returns the argument unchanged. Source § impl<T, U> Into <U> for T where U: From <T>, Source § fn into (self) -> U Calls U::from(self) . That is, this conversion is whatever the implementation of From <T> for U chooses to do. Source § impl<T> ToOwned for T where T: Clone , Source § type Owned = T The resulting type after obtaining ownership. Source § fn to_owned (&self) -> T Creates owned data from borrowed data, usually by cloning. Read more Source § fn clone_into (&self, target: &mut T ) Uses borrowed data to replace owned data, usually by cloning. Read more Source § impl<T> ToString for T where T: Display + ? Sized , Source § fn to_string (&self) -> String Converts the given value to a String . Read more Source § impl<T, U> TryFrom <U> for T where U: Into <T>, Source § type Error = Infallible The type returned in the event of a conversion error. Source § fn try_from (value: U) -> Result <T, <T as TryFrom <U>>:: Error > Performs the conversion. Source § impl<T, U> TryInto <U> for T where U: TryFrom <T>, Source § type Error = <U as TryFrom <T>>:: Error The type returned in the event of a conversion error. Source § fn try_into (self) -> Result <U, <U as TryFrom <T>>:: Error > Performs the conversion. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/reference/config.html#configuration-keys | Configuration - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book Configuration This document explains how Cargo’s configuration system works, as well as available keys or configuration. For configuration of a package through its manifest, see the manifest format . Hierarchical structure Cargo allows local configuration for a particular package as well as global configuration. It looks for configuration files in the current directory and all parent directories. If, for example, Cargo were invoked in /projects/foo/bar/baz , then the following configuration files would be probed for and unified in this order: /projects/foo/bar/baz/.cargo/config.toml /projects/foo/bar/.cargo/config.toml /projects/foo/.cargo/config.toml /projects/.cargo/config.toml /.cargo/config.toml $CARGO_HOME/config.toml which defaults to: Windows: %USERPROFILE%\.cargo\config.toml Unix: $HOME/.cargo/config.toml With this structure, you can specify configuration per-package, and even possibly check it into version control. You can also specify personal defaults with a configuration file in your home directory. If a key is specified in multiple config files, the values will get merged together. Numbers, strings, and booleans will use the value in the deeper config directory taking precedence over ancestor directories, where the home directory is the lowest priority. Arrays will be joined together with higher precedence items being placed later in the merged array. At present, when being invoked from a workspace, Cargo does not read config files from crates within the workspace. i.e. if a workspace has two crates in it, named /projects/foo/bar/baz/mylib and /projects/foo/bar/baz/mybin , and there are Cargo configs at /projects/foo/bar/baz/mylib/.cargo/config.toml and /projects/foo/bar/baz/mybin/.cargo/config.toml , Cargo does not read those configuration files if it is invoked from the workspace root ( /projects/foo/bar/baz/ ). Note: Cargo also reads config files without the .toml extension, such as .cargo/config . Support for the .toml extension was added in version 1.39 and is the preferred form. If both files exist, Cargo will use the file without the extension. Configuration format Configuration files are written in the TOML format (like the manifest), with simple key-value pairs inside of sections (tables). The following is a quick overview of all settings, with detailed descriptions found below. paths = ["/path/to/override"] # path dependency overrides [alias] # command aliases b = "build" c = "check" t = "test" r = "run" rr = "run --release" recursive_example = "rr --example recursions" space_example = ["run", "--release", "--", "\"command list\""] [build] jobs = 1 # number of parallel jobs, defaults to # of CPUs rustc = "rustc" # the rust compiler tool rustc-wrapper = "…" # run this wrapper instead of `rustc` rustc-workspace-wrapper = "…" # run this wrapper instead of `rustc` for workspace members rustdoc = "rustdoc" # the doc generator tool target = "triple" # build for the target triple (ignored by `cargo install`) target-dir = "target" # path of where to place generated artifacts build-dir = "target" # path of where to place intermediate build artifacts rustflags = ["…", "…"] # custom flags to pass to all compiler invocations rustdocflags = ["…", "…"] # custom flags to pass to rustdoc incremental = true # whether or not to enable incremental compilation dep-info-basedir = "…" # path for the base directory for targets in depfiles [credential-alias] # Provides a way to define aliases for credential providers. my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] [doc] browser = "chromium" # browser to use with `cargo doc --open`, # overrides the `BROWSER` environment variable [env] # Set ENV_VAR_NAME=value for any process run by Cargo ENV_VAR_NAME = "value" # Set even if already present in environment ENV_VAR_NAME_2 = { value = "value", force = true } # `value` is relative to the parent of `.cargo/config.toml`, env var will be the full absolute path ENV_VAR_NAME_3 = { value = "relative/path", relative = true } [future-incompat-report] frequency = 'always' # when to display a notification about a future incompat report [cache] auto-clean-frequency = "1 day" # How often to perform automatic cache cleaning [cargo-new] vcs = "none" # VCS to use ('git', 'hg', 'pijul', 'fossil', 'none') [http] debug = false # HTTP debugging proxy = "host:port" # HTTP proxy in libcurl format ssl-version = "tlsv1.3" # TLS version to use ssl-version.max = "tlsv1.3" # maximum TLS version ssl-version.min = "tlsv1.1" # minimum TLS version timeout = 30 # timeout for each HTTP request, in seconds low-speed-limit = 10 # network timeout threshold (bytes/sec) cainfo = "cert.pem" # path to Certificate Authority (CA) bundle proxy-cainfo = "cert.pem" # path to proxy Certificate Authority (CA) bundle check-revoke = true # check for SSL certificate revocation multiplexing = true # HTTP/2 multiplexing user-agent = "…" # the user-agent header [install] root = "/some/path" # `cargo install` destination directory [net] retry = 3 # network retries git-fetch-with-cli = true # use the `git` executable for git operations offline = true # do not access the network [net.ssh] known-hosts = ["..."] # known SSH host keys [patch.<registry>] # Same keys as for [patch] in Cargo.toml [profile.<name>] # Modify profile settings via config. inherits = "dev" # Inherits settings from [profile.dev]. opt-level = 0 # Optimization level. debug = true # Include debug info. split-debuginfo = '...' # Debug info splitting behavior. strip = "none" # Removes symbols or debuginfo. debug-assertions = true # Enables debug assertions. overflow-checks = true # Enables runtime integer overflow checks. lto = false # Sets link-time optimization. panic = 'unwind' # The panic strategy. incremental = true # Incremental compilation. codegen-units = 16 # Number of code generation units. rpath = false # Sets the rpath linking option. [profile.<name>.build-override] # Overrides build-script settings. # Same keys for a normal profile. [profile.<name>.package.<name>] # Override profile for a package. # Same keys for a normal profile (minus `panic`, `lto`, and `rpath`). [resolver] incompatible-rust-versions = "allow" # Specifies how resolver reacts to these [registries.<name>] # registries other than crates.io index = "…" # URL of the registry index token = "…" # authentication token for the registry credential-provider = "cargo:token" # The credential provider for this registry. [registries.crates-io] protocol = "sparse" # The protocol to use to access crates.io. [registry] default = "…" # name of the default registry token = "…" # authentication token for crates.io credential-provider = "cargo:token" # The credential provider for crates.io. global-credential-providers = ["cargo:token"] # The credential providers to use by default. [source.<name>] # source definition and replacement replace-with = "…" # replace this source with the given named source directory = "…" # path to a directory source registry = "…" # URL to a registry source local-registry = "…" # path to a local registry source git = "…" # URL of a git repository source branch = "…" # branch name for the git repository tag = "…" # tag name for the git repository rev = "…" # revision for the git repository [target.<triple>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` rustdocflags = ["…", "…"] # custom flags for `rustdoc` [target.<cfg>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` [target.<triple>.<links>] # `links` build script override rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] quiet = false # whether cargo output is quiet verbose = false # whether cargo provides verbose output color = 'auto' # whether cargo colorizes output hyperlinks = true # whether cargo inserts links into output unicode = true # whether cargo can render output using non-ASCII unicode characters progress.when = 'auto' # whether cargo shows progress bar progress.width = 80 # width of progress bar progress.term-integration = true # whether cargo reports progress to terminal emulator Environment variables Cargo can also be configured through environment variables in addition to the TOML configuration files. For each configuration key of the form foo.bar the environment variable CARGO_FOO_BAR can also be used to define the value. Keys are converted to uppercase, dots and dashes are converted to underscores. For example the target.x86_64-unknown-linux-gnu.runner key can also be defined by the CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER environment variable. Environment variables will take precedence over TOML configuration files. Currently only integer, boolean, string and some array values are supported to be defined by environment variables. Descriptions below indicate which keys support environment variables and otherwise they are not supported due to technical issues . In addition to the system above, Cargo recognizes a few other specific environment variables . Command-line overrides Cargo also accepts arbitrary configuration overrides through the --config command-line option. The argument should be in TOML syntax of KEY=VALUE or provided as a path to an extra configuration file: # With `KEY=VALUE` in TOML syntax cargo --config net.git-fetch-with-cli=true fetch # With a path to a configuration file cargo --config ./path/to/my/extra-config.toml fetch The --config option may be specified multiple times, in which case the values are merged in left-to-right order, using the same merging logic that is used when multiple configuration files apply. Configuration values specified this way take precedence over environment variables, which take precedence over configuration files. When the --config option is provided as an extra configuration file, The configuration file loaded this way follow the same precedence rules as other options specified directly with --config . Some examples of what it looks like using Bourne shell syntax: # Most shells will require escaping. cargo --config http.proxy=\"http://example.com\" … # Spaces may be used. cargo --config "net.git-fetch-with-cli = true" … # TOML array example. Single quotes make it easier to read and write. cargo --config 'build.rustdocflags = ["--html-in-header", "header.html"]' … # Example of a complex TOML key. cargo --config "target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))'.runner = 'my-runner'" … # Example of overriding a profile setting. cargo --config profile.dev.package.image.opt-level=3 … Config-relative paths Paths in config files may be absolute, relative, or a bare name without any path separators. Paths for executables without a path separator will use the PATH environment variable to search for the executable. Paths for non-executables will be relative to where the config value is defined. In particular, rules are: For environment variables, paths are relative to the current working directory. For config values loaded directly from the --config KEY=VALUE option, paths are relative to the current working directory. For config files, paths are relative to the parent directory of the directory where the config files were defined, no matter those files are from either the hierarchical probing or the --config <path> option. Note: To maintain consistency with existing .cargo/config.toml probing behavior, it is by design that a path in a config file passed via --config <path> is also relative to two levels up from the config file itself. To avoid unexpected results, the rule of thumb is putting your extra config files at the same level of discovered .cargo/config.toml in your project. For instance, given a project /my/project , it is recommended to put config files under /my/project/.cargo or a new directory at the same level, such as /my/project/.config . # Relative path examples. [target.x86_64-unknown-linux-gnu] runner = "foo" # Searches `PATH` for `foo`. [source.vendored-sources] # Directory is relative to the parent where `.cargo/config.toml` is located. # For example, `/my/project/.cargo/config.toml` would result in `/my/project/vendor`. directory = "vendor" Executable paths with arguments Some Cargo commands invoke external programs, which can be configured as a path and some number of arguments. The value may be an array of strings like ['/path/to/program', 'somearg'] or a space-separated string like '/path/to/program somearg' . If the path to the executable contains a space, the list form must be used. If Cargo is passing other arguments to the program such as a path to open or run, they will be passed after the last specified argument in the value of an option of this format. If the specified program does not have path separators, Cargo will search PATH for its executable. Credentials Configuration values with sensitive information are stored in the $CARGO_HOME/credentials.toml file. This file is automatically created and updated by cargo login and cargo logout when using the cargo:token credential provider. Tokens are used by some Cargo commands such as cargo publish for authenticating with remote registries. Care should be taken to protect the tokens and to keep them secret. It follows the same format as Cargo config files. [registry] token = "…" # Access token for crates.io [registries.<name>] token = "…" # Access token for the named registry As with most other config values, tokens may be specified with environment variables. The token for crates.io may be specified with the CARGO_REGISTRY_TOKEN environment variable. Tokens for other registries may be specified with environment variables of the form CARGO_REGISTRIES_<name>_TOKEN where <name> is the name of the registry in all capital letters. Note: Cargo also reads and writes credential files without the .toml extension, such as .cargo/credentials . Support for the .toml extension was added in version 1.39. In version 1.68, Cargo writes to the file with the extension by default. However, for backward compatibility reason, when both files exist, Cargo will read and write the file without the extension. Configuration keys This section documents all configuration keys. The description for keys with variable parts are annotated with angled brackets like target.<triple> where the <triple> part can be any target triple like target.x86_64-pc-windows-msvc . paths Type: array of strings (paths) Default: none Environment: not supported An array of paths to local packages which are to be used as overrides for dependencies. For more information see the Overriding Dependencies guide . [alias] Type: string or array of strings Default: see below Environment: CARGO_ALIAS_<name> The [alias] table defines CLI command aliases. For example, running cargo b is an alias for running cargo build . Each key in the table is the subcommand, and the value is the actual command to run. The value may be an array of strings, where the first element is the command and the following are arguments. It may also be a string, which will be split on spaces into subcommand and arguments. The following aliases are built-in to Cargo: [alias] b = "build" c = "check" d = "doc" t = "test" r = "run" rm = "remove" Aliases are not allowed to redefine existing built-in commands. Aliases are recursive: [alias] rr = "run --release" recursive_example = "rr --example recursions" [build] The [build] table controls build-time operations and compiler settings. build.jobs Type: integer or string Default: number of logical CPUs Environment: CARGO_BUILD_JOBS Sets the maximum number of compiler processes to run in parallel. If negative, it sets the maximum number of compiler processes to the number of logical CPUs plus provided value. Should not be 0. If a string default is provided, it sets the value back to defaults. Can be overridden with the --jobs CLI option. build.rustc Type: string (program path) Default: "rustc" Environment: CARGO_BUILD_RUSTC or RUSTC Sets the executable to use for rustc . build.rustc-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WRAPPER or RUSTC_WRAPPER Sets a wrapper to execute instead of rustc . The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). build.rustc-workspace-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER or RUSTC_WORKSPACE_WRAPPER Sets a wrapper to execute instead of rustc , for workspace members only. When building a single-package project without workspaces, that package is considered to be the workspace. The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). It affects the filename hash so that artifacts produced by the wrapper are cached separately. If both rustc-wrapper and rustc-workspace-wrapper are set, then they will be nested: the final invocation is $RUSTC_WRAPPER $RUSTC_WORKSPACE_WRAPPER $RUSTC . build.rustdoc Type: string (program path) Default: "rustdoc" Environment: CARGO_BUILD_RUSTDOC or RUSTDOC Sets the executable to use for rustdoc . build.target Type: string or array of strings Default: host platform Environment: CARGO_BUILD_TARGET The default target platform triples to compile to. Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. Can be overridden with the --target CLI option. [build] target = ["x86_64-unknown-linux-gnu", "i686-unknown-linux-gnu"] build.target-dir Type: string (path) Default: "target" Environment: CARGO_BUILD_TARGET_DIR or CARGO_TARGET_DIR The path to where all compiler output is placed. The default if not specified is a directory named target located at the root of the workspace. Can be overridden with the --target-dir CLI option. For more information see the build cache documentation . build.build-dir Type: string (path) Default: Defaults to the value of build.target-dir Environment: CARGO_BUILD_BUILD_DIR The directory where intermediate build artifacts will be stored. Intermediate artifacts are produced by Rustc/Cargo during the build process. This option supports path templating. Available template variables: {workspace-root} resolves to root of the current workspace. {cargo-cache-home} resolves to CARGO_HOME {workspace-path-hash} resolves to a hash of the manifest path For more information see the build cache documentation . build.rustflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS or RUSTFLAGS Extra command-line flags to pass to rustc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTFLAGS environment variable. RUSTFLAGS environment variable. All matching target.<triple>.rustflags and target.<cfg>.rustflags config entries joined together. build.rustflags config value. Additional flags may also be passed with the cargo rustc command. If the --target flag (or build.target ) is used, then the flags will only be passed to the compiler for the target. Things being built for the host, such as build scripts or proc macros, will not receive the args. Without --target , the flags will be passed to all compiler invocations (including build scripts and proc macros) because dependencies are shared. If you have args that you do not want to pass to build scripts or proc macros and are building for the host, pass --target with the host triple . It is not recommended to pass in flags that Cargo itself usually manages. For example, the flags driven by profiles are best handled by setting the appropriate profile setting. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.rustdocflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTDOCFLAGS or CARGO_ENCODED_RUSTDOCFLAGS or RUSTDOCFLAGS Extra command-line flags to pass to rustdoc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTDOCFLAGS environment variable. RUSTDOCFLAGS environment variable. All matching target.<triple>.rustdocflags config entries joined together. build.rustdocflags config value. Additional flags may also be passed with the cargo rustdoc command. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.incremental Type: bool Default: from profile Environment: CARGO_BUILD_INCREMENTAL or CARGO_INCREMENTAL Whether or not to perform incremental compilation . The default if not set is to use the value from the profile . Otherwise this overrides the setting of all profiles. The CARGO_INCREMENTAL environment variable can be set to 1 to force enable incremental compilation for all profiles, or 0 to disable it. This env var overrides the config setting. build.dep-info-basedir Type: string (path) Default: none Environment: CARGO_BUILD_DEP_INFO_BASEDIR Strips the given path prefix from dep info file paths. This config setting is intended to convert absolute paths to relative paths for tools that require relative paths. The setting itself is a config-relative path. So, for example, a value of "." would strip all paths starting with the parent directory of the .cargo directory. build.pipelining This option is deprecated and unused. Cargo always has pipelining enabled. [credential-alias] Type: string or array of strings Default: empty Environment: CARGO_CREDENTIAL_ALIAS_<name> The [credential-alias] table defines credential provider aliases. These aliases can be referenced as an element of the registry.global-credential-providers array, or as a credential provider for a specific registry under registries.<NAME>.credential-provider . If specified as a string, the value will be split on spaces into path and arguments. For example, to define an alias called my-alias : [credential-alias] my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] See Registry Authentication for more information. [doc] The [doc] table defines options for the cargo doc command. doc.browser Type: string or array of strings ( program path with args ) Default: BROWSER environment variable, or, if that is missing, opening the link in a system specific way This option sets the browser to be used by cargo doc , overriding the BROWSER environment variable when opening documentation with the --open option. [cargo-new] The [cargo-new] table defines defaults for the cargo new command. cargo-new.name This option is deprecated and unused. cargo-new.email This option is deprecated and unused. cargo-new.vcs Type: string Default: "git" or "none" Environment: CARGO_CARGO_NEW_VCS Specifies the source control system to use for initializing a new repository. Valid values are git , hg (for Mercurial), pijul , fossil or none to disable this behavior. Defaults to git , or none if already inside a VCS repository. Can be overridden with the --vcs CLI option. [env] The [env] section allows you to set additional environment variables for build scripts, rustc invocations, cargo run and cargo build . [env] OPENSSL_DIR = "/opt/openssl" By default, the variables specified will not override values that already exist in the environment. This behavior can be changed by setting the force flag. Setting the relative flag evaluates the value as a config-relative path that is relative to the parent directory of the .cargo directory that contains the config.toml file. The value of the environment variable will be the full absolute path. [env] TMPDIR = { value = "/home/tmp", force = true } OPENSSL_DIR = { value = "vendor/openssl", relative = true } [future-incompat-report] The [future-incompat-report] table controls setting for future incompat reporting future-incompat-report.frequency Type: string Default: "always" Environment: CARGO_FUTURE_INCOMPAT_REPORT_FREQUENCY Controls how often we display a notification to the terminal when a future incompat report is available. Possible values: always (default): Always display a notification when a command (e.g. cargo build ) produces a future incompat report never : Never display a notification [cache] The [cache] table defines settings for cargo’s caches. Global caches When running cargo commands, Cargo will automatically track which files you are using within the global cache. Periodically, Cargo will delete files that have not been used for some period of time. It will delete files that have to be downloaded from the network if they have not been used in 3 months. Files that can be generated without network access will be deleted if they have not been used in 1 month. The automatic deletion of files only occurs when running commands that are already doing a significant amount of work, such as all of the build commands ( cargo build , cargo test , cargo check , etc.), and cargo fetch . Automatic deletion is disabled if cargo is offline such as with --offline or --frozen to avoid deleting artifacts that may need to be used if you are offline for a long period of time. Note : This tracking is currently only implemented for the global cache in Cargo’s home directory. This includes registry indexes and source files downloaded from registries and git dependencies. Support for tracking build artifacts is not yet implemented, and tracked in cargo#13136 . Additionally, there is an unstable feature to support manually triggering cache cleaning, and to further customize the configuration options. See the Unstable chapter for more information. cache.auto-clean-frequency Type: string Default: "1 day" Environment: CARGO_CACHE_AUTO_CLEAN_FREQUENCY This option defines how often Cargo will automatically delete unused files in the global cache. This does not define how old the files must be, those thresholds are described above . It supports the following settings: "never" — Never deletes old files. "always" — Checks to delete old files every time Cargo runs. An integer followed by “seconds”, “minutes”, “hours”, “days”, “weeks”, or “months” — Checks to delete old files at most the given time frame. [http] The [http] table defines settings for HTTP behavior. This includes fetching crate dependencies and accessing remote git repositories. http.debug Type: boolean Default: false Environment: CARGO_HTTP_DEBUG If true , enables debugging of HTTP requests. The debug information can be seen by setting the CARGO_LOG=network=debug environment variable (or use network=trace for even more information). Be wary when posting logs from this output in a public location. The output may include headers with authentication tokens which you don’t want to leak! Be sure to review logs before posting them. http.proxy Type: string Default: none Environment: CARGO_HTTP_PROXY or HTTPS_PROXY or https_proxy or http_proxy Sets an HTTP and HTTPS proxy to use. The format is in libcurl format as in [protocol://]host[:port] . If not set, Cargo will also check the http.proxy setting in your global git configuration. If none of those are set, the HTTPS_PROXY or https_proxy environment variables set the proxy for HTTPS requests, and http_proxy sets it for HTTP requests. http.timeout Type: integer Default: 30 Environment: CARGO_HTTP_TIMEOUT or HTTP_TIMEOUT Sets the timeout for each HTTP request, in seconds. http.cainfo Type: string (path) Default: none Environment: CARGO_HTTP_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify TLS certificates. If not specified, Cargo attempts to use the system certificates. http.proxy-cainfo Type: string (path) Default: falls back to http.cainfo if not set Environment: CARGO_HTTP_PROXY_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify proxy TLS certificates. http.check-revoke Type: boolean Default: true (Windows) false (all others) Environment: CARGO_HTTP_CHECK_REVOKE This determines whether or not TLS certificate revocation checks should be performed. This only works on Windows. http.ssl-version Type: string or min/max table Default: none Environment: CARGO_HTTP_SSL_VERSION This sets the minimum TLS version to use. It takes a string, with one of the possible values of "default" , "tlsv1" , "tlsv1.0" , "tlsv1.1" , "tlsv1.2" , or "tlsv1.3" . This may alternatively take a table with two keys, min and max , which each take a string value of the same kind that specifies the minimum and maximum range of TLS versions to use. The default is a minimum version of "tlsv1.0" and a max of the newest version supported on your platform, typically "tlsv1.3" . http.low-speed-limit Type: integer Default: 10 Environment: CARGO_HTTP_LOW_SPEED_LIMIT This setting controls timeout behavior for slow connections. If the average transfer speed in bytes per second is below the given value for http.timeout seconds (default 30 seconds), then the connection is considered too slow and Cargo will abort and retry. http.multiplexing Type: boolean Default: true Environment: CARGO_HTTP_MULTIPLEXING When true , Cargo will attempt to use the HTTP2 protocol with multiplexing. This allows multiple requests to use the same connection, usually improving performance when fetching multiple files. If false , Cargo will use HTTP 1.1 without pipelining. http.user-agent Type: string Default: Cargo’s version Environment: CARGO_HTTP_USER_AGENT Specifies a custom user-agent header to use. The default if not specified is a string that includes Cargo’s version. [install] The [install] table defines defaults for the cargo install command. install.root Type: string (path) Default: Cargo’s home directory Environment: CARGO_INSTALL_ROOT Sets the path to the root directory for installing executables for cargo install . Executables go into a bin directory underneath the root. To track information of installed executables, some extra files, such as .crates.toml and .crates2.json , are also created under this root. The default if not specified is Cargo’s home directory (default .cargo in your home directory). Can be overridden with the --root command-line option. [net] The [net] table controls networking configuration. net.retry Type: integer Default: 3 Environment: CARGO_NET_RETRY Number of times to retry possibly spurious network errors. net.git-fetch-with-cli Type: boolean Default: false Environment: CARGO_NET_GIT_FETCH_WITH_CLI If this is true , then Cargo will use the git executable to fetch registry indexes and git dependencies. If false , then it uses a built-in git library. Setting this to true can be helpful if you have special authentication requirements that Cargo does not support. See Git Authentication for more information about setting up git authentication. net.offline Type: boolean Default: false Environment: CARGO_NET_OFFLINE If this is true , then Cargo will avoid accessing the network, and attempt to proceed with locally cached data. If false , Cargo will access the network as needed, and generate an error if it encounters a network error. Can be overridden with the --offline command-line option. net.ssh The [net.ssh] table contains settings for SSH connections. net.ssh.known-hosts Type: array of strings Default: see description Environment: not supported The known-hosts array contains a list of SSH host keys that should be accepted as valid when connecting to an SSH server (such as for SSH git dependencies). Each entry should be a string in a format similar to OpenSSH known_hosts files. Each string should start with one or more hostnames separated by commas, a space, the key type name, a space, and the base64-encoded key. For example: [net.ssh] known-hosts = [ "example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFO4Q5T0UV0SQevair9PFwoxY9dl4pQl3u5phoqJH3cF" ] Cargo will attempt to load known hosts keys from common locations supported in OpenSSH, and will join those with any listed in a Cargo configuration file. If any matching entry has the correct key, the connection will be allowed. Cargo comes with the host keys for github.com built-in. If those ever change, you can add the new keys to the config or known_hosts file. See Git Authentication for more details. [patch] Just as you can override dependencies using [patch] in Cargo.toml , you can override them in the cargo configuration file to apply those patches to any affected build. The format is identical to the one used in Cargo.toml . Since .cargo/config.toml files are not usually checked into source control, you should prefer patching using Cargo.toml where possible to ensure that other developers can compile your crate in their own environments. Patching through cargo configuration files is generally only appropriate when the patch section is automatically generated by an external build tool. If a given dependency is patched both in a cargo configuration file and a Cargo.toml file, the patch in the configuration file is used. If multiple configuration files patch the same dependency, standard cargo configuration merging is used, which prefers the value defined closest to the current directory, with $HOME/.cargo/config.toml taking the lowest precedence. Relative path dependencies in such a [patch] section are resolved relative to the configuration file they appear in. [profile] The [profile] table can be used to globally change profile settings, and override settings specified in Cargo.toml . It has the same syntax and options as profiles specified in Cargo.toml . See the Profiles chapter for details about the options. [profile.<name>.build-override] Environment: CARGO_PROFILE_<name>_BUILD_OVERRIDE_<key> The build-override table overrides settings for build scripts, proc macros, and their dependencies. It has the same keys as a normal profile. See the overrides section for more details. [profile.<name>.package.<name>] Environment: not supported The package table overrides settings for specific packages. It has the same keys as a normal profile, minus the panic , lto , and rpath settings. See the overrides section for more details. profile.<name>.codegen-units Type: integer Default: See profile docs. Environment: CARGO_PROFILE_<name>_CODEGEN_UNITS See codegen-units . profile.<name>.debug Type: integer or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG See debug . profile.<name>.split-debuginfo Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_SPLIT_DEBUGINFO See split-debuginfo . profile.<name>.debug-assertions Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG_ASSERTIONS See debug-assertions . profile.<name>.incremental Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_INCREMENTAL See incremental . profile.<name>.lto Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_LTO See lto . profile.<name>.overflow-checks Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_OVERFLOW_CHECKS See overflow-checks . profile.<name>.opt-level Type: integer or string Default: See profile docs. Environment: CARGO_PROFILE_<name>_OPT_LEVEL See opt-level . profile.<name>.panic Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_PANIC See panic . profile.<name>.rpath Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_RPATH See rpath . profile.<name>.strip Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_STRIP See strip . [resolver] The [resolver] table overrides dependency resolution behavior for local development (e.g. excludes cargo install ). resolver.incompatible-rust-versions Type: string Default: See resolver docs Environment: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS When resolving which version of a dependency to use, select how versions with incompatible package.rust-version s are treated. Values include: allow : treat rust-version -incompatible versions like any other version fallback : only consider rust-version -incompatible versions if no other version matched Can be overridden with --ignore-rust-version CLI option Setting the dependency’s version requirement higher than any version with a compatible rust-version Specifying the version to cargo update with --precise See the resolver chapter for more details. MSRV: allow is supported on any version fallback is respected as of 1.84 [registries] The [registries] table is used for specifying additional registries . It consists of a sub-table for each named registry. registries.<name>.index Type: string (url) Default: none Environment: CARGO_REGISTRIES_<name>_INDEX Specifies the URL of the index for the registry. registries.<name>.token Type: string Default: none Environment: CARGO_REGISTRIES_<name>_TOKEN Specifies the authentication token for the given registry. This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registries.<name>.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRIES_<name>_CREDENTIAL_PROVIDER Specifies the credential provider for the given registry. If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registries.crates-io.protocol Type: string Default: "sparse" Environment: CARGO_REGISTRIES_CRATES_IO_PROTOCOL Specifies the protocol used to access crates.io. Allowed values are git or sparse . git causes Cargo to clone the entire index of all packages ever published to crates.io from https://github.com/rust-lang/crates.io-index/ . This can have performance implications due to the size of the index. sparse is a newer protocol which uses HTTPS to download only what is necessary from https://index.crates.io/ . This can result in a significant performance improvement for resolving new dependencies in most situations. More information about registry protocols may be found in the Registries chapter . [registry] The [registry] table controls the default registry used when one is not specified. registry.index This value is no longer accepted and should not be used. registry.default Type: string Default: "crates-io" Environment: CARGO_REGISTRY_DEFAULT The name of the registry (from the registries table ) to use by default for registry commands like cargo publish . Can be overridden with the --registry command-line option. registry.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRY_CREDENTIAL_PROVIDER Specifies the credential provider for crates.io . If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registry.token Type: string Default: none Environment: CARGO_REGISTRY_TOKEN Specifies the authentication token for crates.io . This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registry.global-credential-providers Type: array Default: ["cargo:token"] Environment: CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS Specifies the list of global credential providers. If credential provider is not set for a specific registry using registries.<name>.credential-provider , Cargo will use the credential providers in this list. Providers toward the end of the list have precedence. Path and arguments are split on spaces. If the path or arguments contains spaces, the credential provider should be defined in the [credential-alias] table and referenced here by its alias. See Registry Authentication for more information. [source] The [source] table defines the registry sources available. See Source Replacement for more information. It consists of a sub-table for each named source. A source should only define one kind (directory, registry, local-registry, or git). source.<name>.replace-with Type: string Default: none Environment: not supported If set, replace this source with the given named source or named registry. source.<name>.directory Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a directory source. source.<name>.registry Type: string (url) Default: none Environment: not supported Sets the URL to use for a registry source. source.<name>.local-registry Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a local registry source. source.<name>.git Type: string (url) Default: none Environment: not supported Sets the URL to use for a git repository source. source.<name>.branch Type: string Default: none Environment: not supported Sets the branch name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.tag Type: string Default: none Environment: not supported Sets the tag name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.rev Type: string Default: none Environment: not supported Sets the revision to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. [target] The [target] table is used for specifying settings for specific platform targets. It consists of a sub-table which is either a platform triple or a cfg() expression . The given values will be used if the target platform matches either the <triple> value or the <cfg> expression. [target.thumbv7m-none-eabi] linker = "arm-none-eabi-gcc" runner = "my-emulator" rustflags = ["…", "…"] [target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "my-arm-wrapper" rustflags = ["…", "…"] cfg values come from those built-in to the compiler (run rustc --print=cfg to view) and extra --cfg flags passed to rustc (such as those defined in RUSTFLAGS ). Do not try to match on debug_assertions , test , Cargo features like feature="foo" , or values set by build scripts . If using a target spec JSON file, the <triple> value is the filename stem. For example --target foo/bar.json would match [target.bar] . target.<triple>.ar This option is deprecated and unused. target.<triple>.linker Type: string (program path) Default: none Environment: CARGO_TARGET_<triple>_LINKER Specifies the linker which is passed to rustc (via -C linker ) when the <triple> is being compiled for. By default, the linker is not overridden. target.<cfg>.linker This is similar to the target linker , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.runner Type: string or array of strings ( program path with args ) Default: none Environment: CARGO_TARGET_<triple>_RUNNER If a runner is provided, executables for the target <triple> will be executed by invoking the specified runner with the actual executable passed as an argument. This applies to cargo run , cargo test and cargo bench commands. By default, compiled executables are executed directly. target.<cfg>.runner This is similar to the target runner , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.rustflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustflags for more details on the different ways to specific extra flags. target.<cfg>.rustflags This is similar to the target rustflags , but using a cfg() expression . If several <cfg> and <triple> entries match the current target, the flags are joined together. target.<triple>.rustdocflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTDOCFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustdocflags for more details on the different ways to specific extra flags. target.<triple>.<links> The links sub-table provides a way to override a build script . When specified, the build script for the given links library will not be run, and the given values will be used instead. [target.x86_64-unknown-linux-gnu.foo] rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] The [term] table controls terminal output and interaction. term.quiet Type: boolean Default: false Environment: CARGO_TERM_QUIET Controls whether or not log messages are displayed by Cargo. Specifying the --quiet flag will override and force quiet output. Specifying the --verbose flag will override and disable quiet output. term.verbose Type: boolean Default: false Environment: CARGO_TERM_VERBOSE Controls whether or not extra detailed messages are displayed by Cargo. Specifying the --quiet flag will override and disable verbose output. Specifying the --verbose flag will override and force verbose output. term.color Type: string Default: "auto" Environment: CARGO_TERM_COLOR Controls whether or not colored output is used in the terminal. Possible values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. Can be overridden with the --color command-line option. term.hyperlinks Type: bool Default: auto-detect Environment: CARGO_TERM_HYPERLINKS Controls whether or not hyperlinks are used in the terminal. term.unicode Type: bool Default: auto-detect Environment: CARGO_TERM_UNICODE Control whether output can be rendered using non-ASCII unicode characters. term.progress.when Type: string Default: "auto" Environment: CARGO_TERM_PROGRESS_WHEN Controls whether or not progress bar is shown in the terminal. Possible values: auto (default): Intelligently guess whether to show progress bar. always : Always show progress bar. never : Never show progress bar. term.progress.width Type: integer Default: none Environment: CARGO_TERM_PROGRESS_WIDTH Sets the width for progress bar. term.progress.term-integration Type: bool Default: auto-detect Environment: CARGO_TERM_PROGRESS_TERM_INTEGRATION Report progress to the terminal emulator for display in places like the task bar. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#railroad-MetaSeq | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#miscellaneous-options | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---config | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#railroad-MetaItemInner | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/items/external-blocks.html#variadic-functions | External blocks - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [items .extern] External blocks [items .extern .syntax] Syntax ExternBlock → unsafe ? 1 extern Abi ? { InnerAttribute * ExternalItem * } ExternalItem → OuterAttribute * ( MacroInvocationSemi | Visibility ? StaticItem | Visibility ? Function ) Show Railroad ExternBlock unsafe extern Abi { InnerAttribute ExternalItem } ExternalItem OuterAttribute MacroInvocationSemi Visibility StaticItem Visibility Function [items .extern .intro] External blocks provide declarations of items that are not defined in the current crate and are the basis of Rust’s foreign function interface. These are akin to unchecked imports. [items .extern .allowed-kinds] Two kinds of item declarations are allowed in external blocks: functions and statics . [items .extern .safety] Calling unsafe functions or accessing unsafe statics that are declared in external blocks is only allowed in an unsafe context . [items .extern .namespace] The external block defines its functions and statics in the value namespace of the module or block where it is located. [items .extern .unsafe-required] The unsafe keyword is semantically required to appear before the extern keyword on external blocks. [items .extern .edition2024] 2024 Edition differences Prior to the 2024 edition, the unsafe keyword is optional. The safe and unsafe item qualifiers are only allowed if the external block itself is marked as unsafe . [items .extern .fn] Functions [items .extern .fn .body] Functions within external blocks are declared in the same way as other Rust functions, with the exception that they must not have a body and are instead terminated by a semicolon. [items .extern .fn .param-patterns] Patterns are not allowed in parameters, only IDENTIFIER or _ may be used. [items .extern .fn .qualifiers] The safe and unsafe function qualifiers are allowed, but other function qualifiers (e.g. const , async , extern ) are not. [items .extern .fn .foreign-abi] Functions within external blocks may be called by Rust code, just like functions defined in Rust. The Rust compiler automatically translates between the Rust ABI and the foreign ABI. [items .extern .fn .safety] A function declared in an extern block is implicitly unsafe unless the safe function qualifier is present. [items .extern .fn .fn-ptr] When coerced to a function pointer, a function declared in an extern block has type extern "abi" for<'l1, ..., 'lm> fn(A1, ..., An) -> R , where 'l1 , … 'lm are its lifetime parameters, A1 , …, An are the declared types of its parameters, R is the declared return type. [items .extern .static] Statics [items .extern .static .intro] Statics within external blocks are declared in the same way as statics outside of external blocks, except that they do not have an expression initializing their value. [items .extern .static .safety] Unless a static item declared in an extern block is qualified as safe , it is unsafe to access that item, whether or not it’s mutable, because there is nothing guaranteeing that the bit pattern at the static’s memory is valid for the type it is declared with, since some arbitrary (e.g. C) code is in charge of initializing the static. [items .extern .static .mut] Extern statics can be either immutable or mutable just like statics outside of external blocks. [items .extern .static .read-only] An immutable static must be initialized before any Rust code is executed. It is not enough for the static to be initialized before Rust code reads from it. Once Rust code runs, mutating an immutable static (from inside or outside Rust) is UB, except if the mutation happens to bytes inside of an UnsafeCell . [items .extern .abi] ABI [items .extern .abi .intro] The extern keyword can be followed by an optional ABI string. The ABI specifies the calling convention of the functions in the block. The calling convention defines a low-level interface for functions, such as how arguments are placed in registers or on the stack, how return values are passed, and who is responsible for cleaning up the stack. Example #![allow(unused)] fn main() { // Interface to the Windows API. unsafe extern "system" { /* ... */ } } [items .extern .abi .default] If the ABI string is not specified, it defaults to "C" . Note The extern syntax without an explicit ABI is being phased out, so it’s better to always write the ABI explicitly. For more details, see Rust issue #134986 . [items .extern .abi .standard] The following ABI strings are supported on all platforms: [items .extern .abi .rust] unsafe extern "Rust" — The native calling convention for Rust functions and closures. This is the default when a function is declared without using extern fn . The Rust ABI offers no stability guarantees. [items .extern .abi .c] unsafe extern "C" — The “C” ABI matches the default ABI chosen by the dominant C compiler for the target. [items .extern .abi .system] unsafe extern "system" — This is equivalent to extern "C" except on Windows x86_32 where it is equivalent to "stdcall" . Note As the correct underlying ABI on Windows is target-specific, it’s best to use extern "system" when attempting to link Windows API functions that don’t use an explicitly defined ABI. [items .extern .abi .unwind] extern "C-unwind" and extern "system-unwind" — Identical to "C" and "system" , respectively, but with different behavior when the callee unwinds (by panicking or throwing a C++ style exception). [items .extern .abi .platform] There are also some platform-specific ABI strings: [items .extern .abi .cdecl] unsafe extern "cdecl" — The calling convention typically used with x86_32 C code. Only available on x86_32 targets. Corresponds to MSVC’s __cdecl and GCC and clang’s __attribute__((cdecl)) . Note For details, see: https://learn.microsoft.com/en-us/cpp/cpp/cdecl https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl [items .extern .abi .stdcall] unsafe extern "stdcall" — The calling convention typically used by the Win32 API on x86_32. Only available on x86_32 targets. Corresponds to MSVC’s __stdcall and GCC and clang’s __attribute__((stdcall)) . Note For details, see: https://learn.microsoft.com/en-us/cpp/cpp/stdcall https://en.wikipedia.org/wiki/X86_calling_conventions#stdcall [items .extern .abi .win64] unsafe extern "win64" — The Windows x64 ABI. Only available on x86_64 targets. “win64” is the same as the “C” ABI on Windows x86_64 targets. Corresponds to GCC and clang’s __attribute__((ms_abi)) . Note For details, see: https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_x64_calling_convention [items .extern .abi .sysv64] unsafe extern "sysv64" — The System V ABI. Only available on x86_64 targets. “sysv64” is the same as the “C” ABI on non-Windows x86_64 targets. Corresponds to GCC and clang’s __attribute__((sysv_abi)) . Note For details, see: https://wiki.osdev.org/System_V_ABI https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI [items .extern .abi .aapcs] unsafe extern "aapcs" — The soft-float ABI for ARM. Only available on ARM32 targets. “aapcs” is the same as the “C” ABI on soft-float ARM32. Corresponds to clang’s __attribute__((pcs("aapcs"))) . Note For details, see: Arm Procedure Call Standard [items .extern .abi .fastcall] unsafe extern "fastcall" — A “fast” variant of stdcall that passes some arguments in registers. Only available on x86_32 targets. Corresponds to MSVC’s __fastcall and GCC and clang’s __attribute__((fastcall)) . Note For details, see: https://learn.microsoft.com/en-us/cpp/cpp/fastcall https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall [items .extern .abi .thiscall] unsafe extern "thiscall" — The calling convention typically used on C++ class member functions on x86_32 MSVC. Only available on x86_32 targets. Corresponds to MSVC’s __thiscall and GCC and clang’s __attribute__((thiscall)) . Note For details, see: https://en.wikipedia.org/wiki/X86_calling_conventions#thiscall https://learn.microsoft.com/en-us/cpp/cpp/thiscall [items .extern .abi .efiapi] unsafe extern "efiapi" — The ABI used for UEFI functions. Only available on x86 and ARM targets (32bit and 64bit). [items .extern .abi .platform-unwind-variants] Like "C" and "system" , most platform-specific ABI strings also have a corresponding -unwind variant ; specifically, these are: "aapcs-unwind" "cdecl-unwind" "fastcall-unwind" "stdcall-unwind" "sysv64-unwind" "thiscall-unwind" "win64-unwind" [items .extern .variadic] Variadic functions Functions within external blocks may be variadic by specifying ... as the last argument. The variadic parameter may optionally be specified with an identifier. #![allow(unused)] fn main() { unsafe extern "C" { unsafe fn foo(...); unsafe fn bar(x: i32, ...); unsafe fn with_name(format: *const u8, args: ...); // SAFETY: This function guarantees it will not access // variadic arguments. safe fn ignores_variadic_arguments(x: i32, ...); } } Warning The safe qualifier should not be used on a function in an extern block unless that function guarantees that it will not access the variadic arguments at all. Passing an unexpected number of arguments or arguments of unexpected type to a variadic function may lead to undefined behavior . [items .extern .variadic .conventions] Variadic parameters can only be specified within extern blocks with the following ABI strings or their corresponding -unwind variants : "aapcs" "C" "cdecl" "efiapi" "sysv64" "win64" [items .extern .attributes] Attributes on extern blocks [items .extern .attributes .intro] The following attributes control the behavior of external blocks. [items .extern .attributes .link] The link attribute [items .extern .attributes .link .intro] The link attribute specifies the name of a native library that the compiler should link with for the items within an extern block. [items .extern .attributes .link .syntax] It uses the MetaListNameValueStr syntax to specify its inputs. The name key is the name of the native library to link. The kind key is an optional value which specifies the kind of library with the following possible values: [items .extern .attributes .link .dylib] dylib — Indicates a dynamic library. This is the default if kind is not specified. [items .extern .attributes .link .static] static — Indicates a static library. [items .extern .attributes .link .framework] framework — Indicates a macOS framework. This is only valid for macOS targets. [items .extern .attributes .link .raw-dylib] raw-dylib — Indicates a dynamic library where the compiler will generate an import library to link against (see dylib versus raw-dylib below for details). This is only valid for Windows targets. [items .extern .attributes .link .name-requirement] The name key must be included if kind is specified. [items .extern .attributes .link .modifiers] The optional modifiers argument is a way to specify linking modifiers for the library to link. [items .extern .attributes .link .modifiers .syntax] Modifiers are specified as a comma-delimited string with each modifier prefixed with either a + or - to indicate that the modifier is enabled or disabled, respectively. [items .extern .attributes .link .modifiers .multiple] Specifying multiple modifiers arguments in a single link attribute, or multiple identical modifiers in the same modifiers argument is not currently supported. Example: #[link(name = "mylib", kind = "static", modifiers = "+whole-archive")] . [items .extern .attributes .link .wasm_import_module] The wasm_import_module key may be used to specify the WebAssembly module name for the items within an extern block when importing symbols from the host environment. The default module name is env if wasm_import_module is not specified. #[link(name = "crypto")] unsafe extern { // … } #[link(name = "CoreFoundation", kind = "framework")] unsafe extern { // … } #[link(wasm_import_module = "foo")] unsafe extern { // … } [items .extern .attributes .link .empty-block] It is valid to add the link attribute on an empty extern block. You can use this to satisfy the linking requirements of extern blocks elsewhere in your code (including upstream crates) instead of adding the attribute to each extern block. [items .extern .attributes .link .modifiers .bundle] Linking modifiers: bundle [items .extern .attributes .link .modifiers .bundle .allowed-kinds] This modifier is only compatible with the static linking kind. Using any other kind will result in a compiler error. [items .extern .attributes .link .modifiers .bundle .behavior] When building a rlib or staticlib +bundle means that the native static library will be packed into the rlib or staticlib archive, and then retrieved from there during linking of the final binary. [items .extern .attributes .link .modifiers .bundle .behavior-negative] When building a rlib -bundle means that the native static library is registered as a dependency of that rlib “by name”, and object files from it are included only during linking of the final binary, the file search by that name is also performed during final linking. When building a staticlib -bundle means that the native static library is simply not included into the archive and some higher level build system will need to add it later during linking of the final binary. [items .extern .attributes .link .modifiers .bundle .no-effect] This modifier has no effect when building other targets like executables or dynamic libraries. [items .extern .attributes .link .modifiers .bundle .default] The default for this modifier is +bundle . More implementation details about this modifier can be found in bundle documentation for rustc . [items .extern .attributes .link .modifiers .whole-archive] Linking modifiers: whole-archive [items .extern .attributes .link .modifiers .whole-archive .allowed-kinds] This modifier is only compatible with the static linking kind. Using any other kind will result in a compiler error. [items .extern .attributes .link .modifiers .whole-archive .behavior] +whole-archive means that the static library is linked as a whole archive without throwing any object files away. [items .extern .attributes .link .modifiers .whole-archive .default] The default for this modifier is -whole-archive . More implementation details about this modifier can be found in whole-archive documentation for rustc . [items .extern .attributes .link .modifiers .verbatim] Linking modifiers: verbatim [items .extern .attributes .link .modifiers .verbatim .allowed-kinds] This modifier is compatible with all linking kinds. [items .extern .attributes .link .modifiers .verbatim .behavior] +verbatim means that rustc itself won’t add any target-specified library prefixes or suffixes (like lib or .a ) to the library name, and will try its best to ask for the same thing from the linker. [items .extern .attributes .link .modifiers .verbatim .behavior-negative] -verbatim means that rustc will either add a target-specific prefix and suffix to the library name before passing it to linker, or won’t prevent linker from implicitly adding it. [items .extern .attributes .link .modifiers .verbatim .default] The default for this modifier is -verbatim . More implementation details about this modifier can be found in verbatim documentation for rustc . [items .extern .attributes .link .kind-raw-dylib] dylib versus raw-dylib [items .extern .attributes .link .kind-raw-dylib .intro] On Windows, linking against a dynamic library requires that an import library is provided to the linker: this is a special static library that declares all of the symbols exported by the dynamic library in such a way that the linker knows that they have to be dynamically loaded at runtime. [items .extern .attributes .link .kind-raw-dylib .import] Specifying kind = "dylib" instructs the Rust compiler to link an import library based on the name key. The linker will then use its normal library resolution logic to find that import library. Alternatively, specifying kind = "raw-dylib" instructs the compiler to generate an import library during compilation and provide that to the linker instead. [items .extern .attributes .link .kind-raw-dylib .platform-specific] raw-dylib is only supported on Windows. Using it when targeting other platforms will result in a compiler error. [items .extern .attributes .link .import_name_type] The import_name_type key [items .extern .attributes .link .import_name_type .intro] On x86 Windows, names of functions are “decorated” (i.e., have a specific prefix and/or suffix added) to indicate their calling convention. For example, a stdcall calling convention function with the name fn1 that has no arguments would be decorated as _fn1@0 . However, the PE Format does also permit names to have no prefix or be undecorated. Additionally, the MSVC and GNU toolchains use different decorations for the same calling conventions which means, by default, some Win32 functions cannot be called using the raw-dylib link kind via the GNU toolchain. [items .extern .attributes .link .import_name_type .values] To allow for these differences, when using the raw-dylib link kind you may also specify the import_name_type key with one of the following values to change how functions are named in the generated import library: decorated : The function name will be fully-decorated using the MSVC toolchain format. noprefix : The function name will be decorated using the MSVC toolchain format, but skipping the leading ? , @ , or optionally _ . undecorated : The function name will not be decorated. [items .extern .attributes .link .import_name_type .default] If the import_name_type key is not specified, then the function name will be fully-decorated using the target toolchain’s format. [items .extern .attributes .link .import_name_type .variables] Variables are never decorated and so the import_name_type key has no effect on how they are named in the generated import library. [items .extern .attributes .link .import_name_type .platform-specific] The import_name_type key is only supported on x86 Windows. Using it when targeting other platforms will result in a compiler error. [items .extern .attributes .link_name] The link_name attribute [items .extern .attributes .link_name .intro] The link_name attribute may be applied to declarations inside an extern block to specify the symbol to import for the given function or static. Example #![allow(unused)] fn main() { unsafe extern "C" { #[link_name = "actual_symbol_name"] safe fn name_in_rust(); } } [items .extern .attributes .link_name .syntax] The link_name attribute uses the MetaNameValueStr syntax. [items .extern .attributes .link_name .allowed-positions] The link_name attribute may only be applied to a function or static item in an extern block. Note rustc ignores use in other positions but lints against it. This may become an error in the future. [items .extern .attributes .link_name .duplicates] Only the last use of link_name on an item has effect. Note rustc lints against any use preceding the last. This may become an error in the future. [items .extern .attributes .link_name .link_ordinal] The link_name attribute may not be used with the link_ordinal attribute. [items .extern .attributes .link_ordinal] The link_ordinal attribute [items .extern .attributes .link_ordinal .intro] The link_ordinal attribute can be applied on declarations inside an extern block to indicate the numeric ordinal to use when generating the import library to link against. An ordinal is a unique number per symbol exported by a dynamic library on Windows and can be used when the library is being loaded to find that symbol rather than having to look it up by name. Warning link_ordinal should only be used in cases where the ordinal of the symbol is known to be stable: if the ordinal of a symbol is not explicitly set when its containing binary is built then one will be automatically assigned to it, and that assigned ordinal may change between builds of the binary. #![allow(unused)] fn main() { #[cfg(all(windows, target_arch = "x86"))] #[link(name = "exporter", kind = "raw-dylib")] unsafe extern "stdcall" { #[link_ordinal(15)] safe fn imported_function_stdcall(i: i32); } } [items .extern .attributes .link_ordinal .allowed-kinds] This attribute is only used with the raw-dylib linking kind. Using any other kind will result in a compiler error. [items .extern .attributes .link_ordinal .exclusive] Using this attribute with the link_name attribute will result in a compiler error. [items .extern .attributes .fn-parameters] Attributes on function parameters Attributes on extern function parameters follow the same rules and restrictions as regular function parameters . Starting with the 2024 Edition, the unsafe keyword is required semantically. ↩ | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#package-options | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#grammar-Attr | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://aws.amazon.com/blogs/big-data/access-databricks-unity-catalog-data-using-catalog-federation-in-the-aws-glue-data-catalog/ | Access Databricks Unity Catalog data using catalog federation in the AWS Glue Data Catalog | AWS Big Data Blog Skip to Main Content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Blogs Home Blogs Editions AWS Big Data Blog Access Databricks Unity Catalog data using catalog federation in the AWS Glue Data Catalog by Srividya Parthasarathy and Venkat Viswanathan on 12 JAN 2026 in Advanced (300) , Amazon SageMaker , AWS Glue , AWS Lake Formation , Technical How-to Permalink Comments Share AWS has launched the catalog federation capability, enabling direct access to Apache Iceberg tables managed in Databricks Unity Catalog through the AWS Glue Data Catalog . With this integration, you can discover and query Unity Catalog data in Iceberg format using an Iceberg REST API endpoint, while maintaining granular access controls through AWS Lake Formation . This approach significantly reduces operational overhead for managing catalog synchronization and associated costs by alleviating the need to replicate or duplicate datasets between platforms. In this post, we demonstrate how to set up catalog federation between the Glue Data Catalog and Databricks Unity Catalog, enabling data querying using AWS analytics services. Use cases and key benefits This federation capability is particularly valuable if you run multiple data platforms, because you can maintain your existing Iceberg catalog investments while using AWS analytics services. Catalog federation supports read operations and provides the following benefits: Interoperability – You can enable interoperability across different data platforms and tools through Iceberg REST APIs while preserving the value of your established technology investments. Cross-platform analytics – You can connect AWS analytics tools ( Amazon Athena , Amazon Redshift , Apache Spark) to query Iceberg and UniForm tables stored in Databricks Unity Catalog. It supports Databricks on AWS integration with the AWS Glue Iceberg REST Catalog for metadata retrieval, while using Lake Formation for permission management. Metadata management – The solution avoids manual catalog synchronization by making Databricks Unity Catalog databases and tables discoverable within the Data Catalog. You can implement unified governance through Lake Formation for fine-grained access control across federated catalog resources. Solution overview The solution uses catalog federation in the Data Catalog to integrate with Databricks Unity Catalog. The federated catalog created in AWS Glue mirrors the catalog objects in Databricks Unity Catalog and supports OAuth-based authentication. The solution is represented in the following diagram. The integration involves three high-level steps: Set up an integration principal in Databricks Unity Catalog and provide required read access on catalog resources to this principal. Enable OAuth-based authentication for the integration principal. Set up catalog federation to Databricks Unity Catalog in the Glue Data Catalog: Create a federated catalog in the Data Catalog using an AWS Glue connection. Create an AWS Glue connection that uses the credentials of the integration principal (in Step 1) to connect to Databricks Unity Catalog. Configure an AWS Identity and Access Management (IAM) role with permission to Amazon Simple Storage Service (Amazon S3) locations where the Iceberg table data resides. In a cross-account scenario, make sure the bucket policy grants required access to this IAM role. Discover Iceberg tables in federated catalogs using Lake Formation or AWS Glue APIs. During query operations, Lake Formation manages fine-grained permissions on federated resources and credential vending for access to the underlying data. In the following sections, we walk through the steps to integrate the Glue Data Catalog with Databricks Unity Catalog on AWS. Prerequisites To follow along with the solution presented in this post, you must have the following prerequisites: Databricks Workspace (on AWS) with Databricks Unity Catalog configured. An IAM role that is a Lake Formation data lake administrator in your AWS account. A data lake administrator is an IAM principal that can register S3 locations, access the Data Catalog, grant Lake Formation permissions to other users, and view AWS CloudTrail logs. See Create a data lake administrator for more information. Configure Databricks Unity Catalog for external access Catalog federation to a Databricks Unity Catalog uses the OAuth2 credentials of a Databricks service principal configured in the workspace admin settings. This authentication mechanism allows the Data Catalog to access the metadata of various objects (such as catalogs, databases, and tables) within Databricks Unity Catalog, based on the privileges associated with the service principal. For proper functionality, grant the service principal with the necessary permissions (read permission on catalog, schema, and tables) to read the metadata of these objects and allow access from external engines. Next, catalog federation enables discovery and query of Iceberg tables in your Databricks Unity Catalog. For reading delta tables, enable UniForm on a Delta Lake table in Databricks to generate Iceberg metadata. For more information, refer to Read Delta tables with Iceberg clients . Follow the Databricks tutorial and documentation to create the service principal and associated privileges in your Databricks workspace. For this post, we use a service principal named integrationprincipal that is configured with required permissions (SELECT, USE CATALOG, USE SCHEMA) on Databricks Unity Catalog objects and will be used for authentication to catalog instance. Catalog federation supports OAuth2 authentication, so enable OAuth for the service principal and note down the client_id and client_secret for later use. Set up Data Catalog federation with Databricks Unity Catalog Now that you have service principal access for Databricks Unity Catalog, you can set up catalog federation in the Data Catalog. To do so, you create an AWS Secrets Manager secret and create an IAM role for catalog federation. Create secret Complete the following steps to create a secret: Sign in to the AWS Management Console using an IAM role with access to Secrets Manager. On the Secrets Manager console, choose Store a new secret and Other type of secret . Set the key-value pair: Key: USER_MANAGED_CLIENT_APPLICATION_CLIENT_SECRET Value: The client secret noted earlier Choose Next . Enter a name for your secret (for this post, we use dbx ). Choose Store . Create IAM role for catalog federation As the catalog owner of a federated catalog in the Data Catalog, you can use Lake Formation to implement comprehensive access controls, including table filters, column filters, and row filters, as well as tag-based access for your data teams. Lake Formation requires an IAM role with permissions to access the underlying S3 locations of your external catalog. In this step, you create an IAM role that enables the AWS Glue connection to access Secrets Manager, optional virtual private cloud (VPC) configurations, and Lake Formation to manage credential vending for the S3 bucket and prefix: Secrets Manager access – The AWS Glue connection requires permissions to retrieve secret values from Secrets Manager for OAuth tokens stored for your Databricks Unity service connection. VPC access (optional) – When using VPC endpoints to restrict connectivity to your Databricks Unity account, the AWS Glue connection needs permissions to describe and utilize VPC network interfaces. This configuration provides secure, controlled access to both your stored credentials and network resources while maintaining proper isolation through VPC endpoints. S3 bucket and AWS KMS key permission – The AWS Glue connection requires Amazon S3 permissions to read certificates if used in the connection setup. Additionally, Lake Formation requires read permissions on the bucket and prefix where the remote catalog table data resides. If the data is encrypted using an AWS Key Management Service (AWS KMS) key, additional AWS KMS permissions are required. Complete the following steps: Create an IAM role called LFDataAccessRole with the following policies: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "secretsmanager:GetSecretValue", "secretsmanager:DescribeSecret" ], "Resource": [ "<secrets manager ARN>" ] }, { "Effect": "Allow", "Action": [ "ec2:CreateNetworkInterface", "ec2:DeleteNetworkInterface", "ec2:DescribeNetworkInterfaces" ], "Resource": "*", "Condition": { "ArnEquals": { "ec2:Vpc": "arn:aws:ec2:region:account-id:vpc/<vpc-id>", "ec2:Subnet": [ "arn:aws:ec2:region:account-id:subnet/<subnet-id>" ] } } }, { # Required when using custom cert to sign requests. "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3 :::<bucketname>/<certpath>" ] }, { # Required when using customer managed encryption key for s3 "Effect": "Allow", "Action": [ "kms:decrypt", "kms:encrypt" ], "Resource": [ "<kmsKey>" ] } ] } Configure the role with the following trust policy: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": ["glue.amazonaws.com","lakeformation.amazonaws.com"] }, "Action": "sts:AssumeRole" } ] } Create federated catalog in Data Catalog AWS Glue supports the DATABRICKSICEBERGRESTCATALOG connection type for connecting the Data Catalog with managed Databricks Unity Catalog. This AWS Glue connector supports OAuth2 authentication for discovering metadata in Databricks Unity Catalog. Complete the following steps to create the federated catalog: Sign in to the console as a data lake admin. On the Lake Formation console, choose Catalogs in the navigation pane. Choose Create catalog . For Name , enter a name for your catalog. For Catalog name in Databricks , enter the name of a catalog existing in Databricks Unity Catalog. For Connection name , enter a name for the AWS Glue connection. For Workspace URL , enter the Unity Iceberg REST API URL (in format https:// <workspace-url> /cloud.databricks.com ). For Authentication , provide the following information: For Authentication type , choose OAuth2 . Alternatively, you can choose Custom authentication . For Custom authentication , an access token is created, refreshed, and managed by the customer’s application or system and stored using Secrets Manager. For Token URL , enter the token authentication server URL. For OAuth Client ID , enter the client_id for integrationprincipal . For OAuth Secret , enter the secret ARN that you created in the previous step. Alternatively, you can provide the client_secret directly. For Token URL parameter map scope , provide the API scope supported. If you have AWS PrivateLink set up or a proxy set up, you can provide network details under Settings for network configurations . For Register Glue connection with Lake Formation , choose the IAM role ( LFDataAccessRole ) created earlier to manage data access using Lake Formation. When the setup is done using AWS Command Line Interface (AWS CLI) commands, you have options to create two separate IAM roles: IAM role with policies to access network and secrets, which AWS Glue assumes to manage authentication IAM role with access to the S3 bucket, which Lake Formation assumes to manage credential vending for data access On the console, this setup is simplified with a single role having combined policies. For more details, refer to Federate to Databricks Unity Catalog . To test the connection, choose Run test . You can proceed to create the catalog. After you create the catalog, you can see the databases and tables in Databricks Unity Catalog listed under the federated catalog. You can implement fine-grained access control on the tables by applying row and column filters using Lake Formation. The following video shows the catalog federation setup with Databricks Unity Catalog. Discover and query the data using Athena In this post, we show how to use the Athena query editor to discover and query the Databricks Unity Catalog tables. On the Athena console, run the following query to access the federated table: SELECT * FROM "customerschema"."person" limit 10; The following video demonstrates querying the federated table from Athena. If you use the Amazon Redshift query engine, you must create a resource link on the federated database and grant permission on the resource link to the user or role. This database resource link is automounted under awsdatacatalog based on the permission granted for the user or role and available for querying. For instructions, refer to Creating resource links. Clean up To clean up your resources, complete the following steps: Delete the catalog and namespace in Databricks Unity Catalog for this post. Drop the resources in the Data Catalog and Lake Formation created for this post. Delete the IAM roles and S3 buckets used for this post. Delete any VPC and KMS keys if used for this post. Conclusion In this post, we explored the key elements of catalog federation and its architectural design, illustrating the interaction between the AWS Glue Data Catalog and Databricks Unity Catalog through centralized authorization and credential distribution for protected data access. By removing the requirement for complicated synchronization workflows, catalog federation makes it possible to query Iceberg data on Amazon S3 directly at its source using AWS analytics services with data governance across multi-catalog platforms. Try out the solution for your own use case, and share your feedback and questions in the comments. About the Authors Srividya Parthasarathy Srividya is a Senior Big Data Architect on the AWS Lake Formation team. She works with the product team and customers to build robust features and solutions for their analytical data platform. She enjoys building data mesh solutions and sharing them with the community. Venkatavaradhan (Venkat) Viswanathan Venkat” is a Global Partner Solutions Architect at Amazon Web Services. Venkat is a Technology Strategy Leader in Data, AI, ML, Generative AI, and Advanced Analytics. Venkat is a Global SME for Databricks and helps AWS customers design, build, secure, and optimize Databricks workloads on AWS. Loading comments… Resources Amazon Athena Amazon EMR Amazon Kinesis Amazon MSK Amazon QuickSight Amazon Redshift AWS Glue Follow Twitter Facebook LinkedIn Twitch Email Updates Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts <path d="M14.8571 13.1432V6.28606C14.6667 6.50035 14.4613 6.69678 14.2411 6.87535C12.6458 8.10154 11.378 9.10749 10.4375 9.89321C10.1339 10.1492 9.88691 10.3486 9.69643 10.4914C9.50595 10.6343 9.24851 10.7786 8.92411 10.9245C8.5997 11.0703 8.29464 11.1432 8.00893 11.1432H8H7.99107C7.70536 11.1432 7.4003 11.0703 7.07589 10.9245C6.75149 10.7786 6.49405 10.6343 6.30357 10.4914C6.1131 10.3486 5.86607 10.1492 5.5625 9.89321C4.62202 9.10749 3.35417 8.10154 1.75893 6.87535C1.53869 6.69678 1.33333 6.50035 1.14286 6.28606V13.1432C1.14286 13.2206 1.17113 13.2876 1.22768 13.3441C1.28423 13.4006 1.35119 13.4289 1.42857 13.4289H14.5714C14.6488 13.4289 14.7158 13.4006 14.7723 13.3441C14.8289 13.2876 14.8571 13.2206 14.8571 13.1432ZM14.8571 3.75928C14.8571 3.74737 14.8571 3.71463 14.8571 3.6 | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/reference/config.html#buildrustdoc | Configuration - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book Configuration This document explains how Cargo’s configuration system works, as well as available keys or configuration. For configuration of a package through its manifest, see the manifest format . Hierarchical structure Cargo allows local configuration for a particular package as well as global configuration. It looks for configuration files in the current directory and all parent directories. If, for example, Cargo were invoked in /projects/foo/bar/baz , then the following configuration files would be probed for and unified in this order: /projects/foo/bar/baz/.cargo/config.toml /projects/foo/bar/.cargo/config.toml /projects/foo/.cargo/config.toml /projects/.cargo/config.toml /.cargo/config.toml $CARGO_HOME/config.toml which defaults to: Windows: %USERPROFILE%\.cargo\config.toml Unix: $HOME/.cargo/config.toml With this structure, you can specify configuration per-package, and even possibly check it into version control. You can also specify personal defaults with a configuration file in your home directory. If a key is specified in multiple config files, the values will get merged together. Numbers, strings, and booleans will use the value in the deeper config directory taking precedence over ancestor directories, where the home directory is the lowest priority. Arrays will be joined together with higher precedence items being placed later in the merged array. At present, when being invoked from a workspace, Cargo does not read config files from crates within the workspace. i.e. if a workspace has two crates in it, named /projects/foo/bar/baz/mylib and /projects/foo/bar/baz/mybin , and there are Cargo configs at /projects/foo/bar/baz/mylib/.cargo/config.toml and /projects/foo/bar/baz/mybin/.cargo/config.toml , Cargo does not read those configuration files if it is invoked from the workspace root ( /projects/foo/bar/baz/ ). Note: Cargo also reads config files without the .toml extension, such as .cargo/config . Support for the .toml extension was added in version 1.39 and is the preferred form. If both files exist, Cargo will use the file without the extension. Configuration format Configuration files are written in the TOML format (like the manifest), with simple key-value pairs inside of sections (tables). The following is a quick overview of all settings, with detailed descriptions found below. paths = ["/path/to/override"] # path dependency overrides [alias] # command aliases b = "build" c = "check" t = "test" r = "run" rr = "run --release" recursive_example = "rr --example recursions" space_example = ["run", "--release", "--", "\"command list\""] [build] jobs = 1 # number of parallel jobs, defaults to # of CPUs rustc = "rustc" # the rust compiler tool rustc-wrapper = "…" # run this wrapper instead of `rustc` rustc-workspace-wrapper = "…" # run this wrapper instead of `rustc` for workspace members rustdoc = "rustdoc" # the doc generator tool target = "triple" # build for the target triple (ignored by `cargo install`) target-dir = "target" # path of where to place generated artifacts build-dir = "target" # path of where to place intermediate build artifacts rustflags = ["…", "…"] # custom flags to pass to all compiler invocations rustdocflags = ["…", "…"] # custom flags to pass to rustdoc incremental = true # whether or not to enable incremental compilation dep-info-basedir = "…" # path for the base directory for targets in depfiles [credential-alias] # Provides a way to define aliases for credential providers. my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] [doc] browser = "chromium" # browser to use with `cargo doc --open`, # overrides the `BROWSER` environment variable [env] # Set ENV_VAR_NAME=value for any process run by Cargo ENV_VAR_NAME = "value" # Set even if already present in environment ENV_VAR_NAME_2 = { value = "value", force = true } # `value` is relative to the parent of `.cargo/config.toml`, env var will be the full absolute path ENV_VAR_NAME_3 = { value = "relative/path", relative = true } [future-incompat-report] frequency = 'always' # when to display a notification about a future incompat report [cache] auto-clean-frequency = "1 day" # How often to perform automatic cache cleaning [cargo-new] vcs = "none" # VCS to use ('git', 'hg', 'pijul', 'fossil', 'none') [http] debug = false # HTTP debugging proxy = "host:port" # HTTP proxy in libcurl format ssl-version = "tlsv1.3" # TLS version to use ssl-version.max = "tlsv1.3" # maximum TLS version ssl-version.min = "tlsv1.1" # minimum TLS version timeout = 30 # timeout for each HTTP request, in seconds low-speed-limit = 10 # network timeout threshold (bytes/sec) cainfo = "cert.pem" # path to Certificate Authority (CA) bundle proxy-cainfo = "cert.pem" # path to proxy Certificate Authority (CA) bundle check-revoke = true # check for SSL certificate revocation multiplexing = true # HTTP/2 multiplexing user-agent = "…" # the user-agent header [install] root = "/some/path" # `cargo install` destination directory [net] retry = 3 # network retries git-fetch-with-cli = true # use the `git` executable for git operations offline = true # do not access the network [net.ssh] known-hosts = ["..."] # known SSH host keys [patch.<registry>] # Same keys as for [patch] in Cargo.toml [profile.<name>] # Modify profile settings via config. inherits = "dev" # Inherits settings from [profile.dev]. opt-level = 0 # Optimization level. debug = true # Include debug info. split-debuginfo = '...' # Debug info splitting behavior. strip = "none" # Removes symbols or debuginfo. debug-assertions = true # Enables debug assertions. overflow-checks = true # Enables runtime integer overflow checks. lto = false # Sets link-time optimization. panic = 'unwind' # The panic strategy. incremental = true # Incremental compilation. codegen-units = 16 # Number of code generation units. rpath = false # Sets the rpath linking option. [profile.<name>.build-override] # Overrides build-script settings. # Same keys for a normal profile. [profile.<name>.package.<name>] # Override profile for a package. # Same keys for a normal profile (minus `panic`, `lto`, and `rpath`). [resolver] incompatible-rust-versions = "allow" # Specifies how resolver reacts to these [registries.<name>] # registries other than crates.io index = "…" # URL of the registry index token = "…" # authentication token for the registry credential-provider = "cargo:token" # The credential provider for this registry. [registries.crates-io] protocol = "sparse" # The protocol to use to access crates.io. [registry] default = "…" # name of the default registry token = "…" # authentication token for crates.io credential-provider = "cargo:token" # The credential provider for crates.io. global-credential-providers = ["cargo:token"] # The credential providers to use by default. [source.<name>] # source definition and replacement replace-with = "…" # replace this source with the given named source directory = "…" # path to a directory source registry = "…" # URL to a registry source local-registry = "…" # path to a local registry source git = "…" # URL of a git repository source branch = "…" # branch name for the git repository tag = "…" # tag name for the git repository rev = "…" # revision for the git repository [target.<triple>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` rustdocflags = ["…", "…"] # custom flags for `rustdoc` [target.<cfg>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` [target.<triple>.<links>] # `links` build script override rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] quiet = false # whether cargo output is quiet verbose = false # whether cargo provides verbose output color = 'auto' # whether cargo colorizes output hyperlinks = true # whether cargo inserts links into output unicode = true # whether cargo can render output using non-ASCII unicode characters progress.when = 'auto' # whether cargo shows progress bar progress.width = 80 # width of progress bar progress.term-integration = true # whether cargo reports progress to terminal emulator Environment variables Cargo can also be configured through environment variables in addition to the TOML configuration files. For each configuration key of the form foo.bar the environment variable CARGO_FOO_BAR can also be used to define the value. Keys are converted to uppercase, dots and dashes are converted to underscores. For example the target.x86_64-unknown-linux-gnu.runner key can also be defined by the CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER environment variable. Environment variables will take precedence over TOML configuration files. Currently only integer, boolean, string and some array values are supported to be defined by environment variables. Descriptions below indicate which keys support environment variables and otherwise they are not supported due to technical issues . In addition to the system above, Cargo recognizes a few other specific environment variables . Command-line overrides Cargo also accepts arbitrary configuration overrides through the --config command-line option. The argument should be in TOML syntax of KEY=VALUE or provided as a path to an extra configuration file: # With `KEY=VALUE` in TOML syntax cargo --config net.git-fetch-with-cli=true fetch # With a path to a configuration file cargo --config ./path/to/my/extra-config.toml fetch The --config option may be specified multiple times, in which case the values are merged in left-to-right order, using the same merging logic that is used when multiple configuration files apply. Configuration values specified this way take precedence over environment variables, which take precedence over configuration files. When the --config option is provided as an extra configuration file, The configuration file loaded this way follow the same precedence rules as other options specified directly with --config . Some examples of what it looks like using Bourne shell syntax: # Most shells will require escaping. cargo --config http.proxy=\"http://example.com\" … # Spaces may be used. cargo --config "net.git-fetch-with-cli = true" … # TOML array example. Single quotes make it easier to read and write. cargo --config 'build.rustdocflags = ["--html-in-header", "header.html"]' … # Example of a complex TOML key. cargo --config "target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))'.runner = 'my-runner'" … # Example of overriding a profile setting. cargo --config profile.dev.package.image.opt-level=3 … Config-relative paths Paths in config files may be absolute, relative, or a bare name without any path separators. Paths for executables without a path separator will use the PATH environment variable to search for the executable. Paths for non-executables will be relative to where the config value is defined. In particular, rules are: For environment variables, paths are relative to the current working directory. For config values loaded directly from the --config KEY=VALUE option, paths are relative to the current working directory. For config files, paths are relative to the parent directory of the directory where the config files were defined, no matter those files are from either the hierarchical probing or the --config <path> option. Note: To maintain consistency with existing .cargo/config.toml probing behavior, it is by design that a path in a config file passed via --config <path> is also relative to two levels up from the config file itself. To avoid unexpected results, the rule of thumb is putting your extra config files at the same level of discovered .cargo/config.toml in your project. For instance, given a project /my/project , it is recommended to put config files under /my/project/.cargo or a new directory at the same level, such as /my/project/.config . # Relative path examples. [target.x86_64-unknown-linux-gnu] runner = "foo" # Searches `PATH` for `foo`. [source.vendored-sources] # Directory is relative to the parent where `.cargo/config.toml` is located. # For example, `/my/project/.cargo/config.toml` would result in `/my/project/vendor`. directory = "vendor" Executable paths with arguments Some Cargo commands invoke external programs, which can be configured as a path and some number of arguments. The value may be an array of strings like ['/path/to/program', 'somearg'] or a space-separated string like '/path/to/program somearg' . If the path to the executable contains a space, the list form must be used. If Cargo is passing other arguments to the program such as a path to open or run, they will be passed after the last specified argument in the value of an option of this format. If the specified program does not have path separators, Cargo will search PATH for its executable. Credentials Configuration values with sensitive information are stored in the $CARGO_HOME/credentials.toml file. This file is automatically created and updated by cargo login and cargo logout when using the cargo:token credential provider. Tokens are used by some Cargo commands such as cargo publish for authenticating with remote registries. Care should be taken to protect the tokens and to keep them secret. It follows the same format as Cargo config files. [registry] token = "…" # Access token for crates.io [registries.<name>] token = "…" # Access token for the named registry As with most other config values, tokens may be specified with environment variables. The token for crates.io may be specified with the CARGO_REGISTRY_TOKEN environment variable. Tokens for other registries may be specified with environment variables of the form CARGO_REGISTRIES_<name>_TOKEN where <name> is the name of the registry in all capital letters. Note: Cargo also reads and writes credential files without the .toml extension, such as .cargo/credentials . Support for the .toml extension was added in version 1.39. In version 1.68, Cargo writes to the file with the extension by default. However, for backward compatibility reason, when both files exist, Cargo will read and write the file without the extension. Configuration keys This section documents all configuration keys. The description for keys with variable parts are annotated with angled brackets like target.<triple> where the <triple> part can be any target triple like target.x86_64-pc-windows-msvc . paths Type: array of strings (paths) Default: none Environment: not supported An array of paths to local packages which are to be used as overrides for dependencies. For more information see the Overriding Dependencies guide . [alias] Type: string or array of strings Default: see below Environment: CARGO_ALIAS_<name> The [alias] table defines CLI command aliases. For example, running cargo b is an alias for running cargo build . Each key in the table is the subcommand, and the value is the actual command to run. The value may be an array of strings, where the first element is the command and the following are arguments. It may also be a string, which will be split on spaces into subcommand and arguments. The following aliases are built-in to Cargo: [alias] b = "build" c = "check" d = "doc" t = "test" r = "run" rm = "remove" Aliases are not allowed to redefine existing built-in commands. Aliases are recursive: [alias] rr = "run --release" recursive_example = "rr --example recursions" [build] The [build] table controls build-time operations and compiler settings. build.jobs Type: integer or string Default: number of logical CPUs Environment: CARGO_BUILD_JOBS Sets the maximum number of compiler processes to run in parallel. If negative, it sets the maximum number of compiler processes to the number of logical CPUs plus provided value. Should not be 0. If a string default is provided, it sets the value back to defaults. Can be overridden with the --jobs CLI option. build.rustc Type: string (program path) Default: "rustc" Environment: CARGO_BUILD_RUSTC or RUSTC Sets the executable to use for rustc . build.rustc-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WRAPPER or RUSTC_WRAPPER Sets a wrapper to execute instead of rustc . The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). build.rustc-workspace-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER or RUSTC_WORKSPACE_WRAPPER Sets a wrapper to execute instead of rustc , for workspace members only. When building a single-package project without workspaces, that package is considered to be the workspace. The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). It affects the filename hash so that artifacts produced by the wrapper are cached separately. If both rustc-wrapper and rustc-workspace-wrapper are set, then they will be nested: the final invocation is $RUSTC_WRAPPER $RUSTC_WORKSPACE_WRAPPER $RUSTC . build.rustdoc Type: string (program path) Default: "rustdoc" Environment: CARGO_BUILD_RUSTDOC or RUSTDOC Sets the executable to use for rustdoc . build.target Type: string or array of strings Default: host platform Environment: CARGO_BUILD_TARGET The default target platform triples to compile to. Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. Can be overridden with the --target CLI option. [build] target = ["x86_64-unknown-linux-gnu", "i686-unknown-linux-gnu"] build.target-dir Type: string (path) Default: "target" Environment: CARGO_BUILD_TARGET_DIR or CARGO_TARGET_DIR The path to where all compiler output is placed. The default if not specified is a directory named target located at the root of the workspace. Can be overridden with the --target-dir CLI option. For more information see the build cache documentation . build.build-dir Type: string (path) Default: Defaults to the value of build.target-dir Environment: CARGO_BUILD_BUILD_DIR The directory where intermediate build artifacts will be stored. Intermediate artifacts are produced by Rustc/Cargo during the build process. This option supports path templating. Available template variables: {workspace-root} resolves to root of the current workspace. {cargo-cache-home} resolves to CARGO_HOME {workspace-path-hash} resolves to a hash of the manifest path For more information see the build cache documentation . build.rustflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS or RUSTFLAGS Extra command-line flags to pass to rustc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTFLAGS environment variable. RUSTFLAGS environment variable. All matching target.<triple>.rustflags and target.<cfg>.rustflags config entries joined together. build.rustflags config value. Additional flags may also be passed with the cargo rustc command. If the --target flag (or build.target ) is used, then the flags will only be passed to the compiler for the target. Things being built for the host, such as build scripts or proc macros, will not receive the args. Without --target , the flags will be passed to all compiler invocations (including build scripts and proc macros) because dependencies are shared. If you have args that you do not want to pass to build scripts or proc macros and are building for the host, pass --target with the host triple . It is not recommended to pass in flags that Cargo itself usually manages. For example, the flags driven by profiles are best handled by setting the appropriate profile setting. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.rustdocflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTDOCFLAGS or CARGO_ENCODED_RUSTDOCFLAGS or RUSTDOCFLAGS Extra command-line flags to pass to rustdoc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTDOCFLAGS environment variable. RUSTDOCFLAGS environment variable. All matching target.<triple>.rustdocflags config entries joined together. build.rustdocflags config value. Additional flags may also be passed with the cargo rustdoc command. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.incremental Type: bool Default: from profile Environment: CARGO_BUILD_INCREMENTAL or CARGO_INCREMENTAL Whether or not to perform incremental compilation . The default if not set is to use the value from the profile . Otherwise this overrides the setting of all profiles. The CARGO_INCREMENTAL environment variable can be set to 1 to force enable incremental compilation for all profiles, or 0 to disable it. This env var overrides the config setting. build.dep-info-basedir Type: string (path) Default: none Environment: CARGO_BUILD_DEP_INFO_BASEDIR Strips the given path prefix from dep info file paths. This config setting is intended to convert absolute paths to relative paths for tools that require relative paths. The setting itself is a config-relative path. So, for example, a value of "." would strip all paths starting with the parent directory of the .cargo directory. build.pipelining This option is deprecated and unused. Cargo always has pipelining enabled. [credential-alias] Type: string or array of strings Default: empty Environment: CARGO_CREDENTIAL_ALIAS_<name> The [credential-alias] table defines credential provider aliases. These aliases can be referenced as an element of the registry.global-credential-providers array, or as a credential provider for a specific registry under registries.<NAME>.credential-provider . If specified as a string, the value will be split on spaces into path and arguments. For example, to define an alias called my-alias : [credential-alias] my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] See Registry Authentication for more information. [doc] The [doc] table defines options for the cargo doc command. doc.browser Type: string or array of strings ( program path with args ) Default: BROWSER environment variable, or, if that is missing, opening the link in a system specific way This option sets the browser to be used by cargo doc , overriding the BROWSER environment variable when opening documentation with the --open option. [cargo-new] The [cargo-new] table defines defaults for the cargo new command. cargo-new.name This option is deprecated and unused. cargo-new.email This option is deprecated and unused. cargo-new.vcs Type: string Default: "git" or "none" Environment: CARGO_CARGO_NEW_VCS Specifies the source control system to use for initializing a new repository. Valid values are git , hg (for Mercurial), pijul , fossil or none to disable this behavior. Defaults to git , or none if already inside a VCS repository. Can be overridden with the --vcs CLI option. [env] The [env] section allows you to set additional environment variables for build scripts, rustc invocations, cargo run and cargo build . [env] OPENSSL_DIR = "/opt/openssl" By default, the variables specified will not override values that already exist in the environment. This behavior can be changed by setting the force flag. Setting the relative flag evaluates the value as a config-relative path that is relative to the parent directory of the .cargo directory that contains the config.toml file. The value of the environment variable will be the full absolute path. [env] TMPDIR = { value = "/home/tmp", force = true } OPENSSL_DIR = { value = "vendor/openssl", relative = true } [future-incompat-report] The [future-incompat-report] table controls setting for future incompat reporting future-incompat-report.frequency Type: string Default: "always" Environment: CARGO_FUTURE_INCOMPAT_REPORT_FREQUENCY Controls how often we display a notification to the terminal when a future incompat report is available. Possible values: always (default): Always display a notification when a command (e.g. cargo build ) produces a future incompat report never : Never display a notification [cache] The [cache] table defines settings for cargo’s caches. Global caches When running cargo commands, Cargo will automatically track which files you are using within the global cache. Periodically, Cargo will delete files that have not been used for some period of time. It will delete files that have to be downloaded from the network if they have not been used in 3 months. Files that can be generated without network access will be deleted if they have not been used in 1 month. The automatic deletion of files only occurs when running commands that are already doing a significant amount of work, such as all of the build commands ( cargo build , cargo test , cargo check , etc.), and cargo fetch . Automatic deletion is disabled if cargo is offline such as with --offline or --frozen to avoid deleting artifacts that may need to be used if you are offline for a long period of time. Note : This tracking is currently only implemented for the global cache in Cargo’s home directory. This includes registry indexes and source files downloaded from registries and git dependencies. Support for tracking build artifacts is not yet implemented, and tracked in cargo#13136 . Additionally, there is an unstable feature to support manually triggering cache cleaning, and to further customize the configuration options. See the Unstable chapter for more information. cache.auto-clean-frequency Type: string Default: "1 day" Environment: CARGO_CACHE_AUTO_CLEAN_FREQUENCY This option defines how often Cargo will automatically delete unused files in the global cache. This does not define how old the files must be, those thresholds are described above . It supports the following settings: "never" — Never deletes old files. "always" — Checks to delete old files every time Cargo runs. An integer followed by “seconds”, “minutes”, “hours”, “days”, “weeks”, or “months” — Checks to delete old files at most the given time frame. [http] The [http] table defines settings for HTTP behavior. This includes fetching crate dependencies and accessing remote git repositories. http.debug Type: boolean Default: false Environment: CARGO_HTTP_DEBUG If true , enables debugging of HTTP requests. The debug information can be seen by setting the CARGO_LOG=network=debug environment variable (or use network=trace for even more information). Be wary when posting logs from this output in a public location. The output may include headers with authentication tokens which you don’t want to leak! Be sure to review logs before posting them. http.proxy Type: string Default: none Environment: CARGO_HTTP_PROXY or HTTPS_PROXY or https_proxy or http_proxy Sets an HTTP and HTTPS proxy to use. The format is in libcurl format as in [protocol://]host[:port] . If not set, Cargo will also check the http.proxy setting in your global git configuration. If none of those are set, the HTTPS_PROXY or https_proxy environment variables set the proxy for HTTPS requests, and http_proxy sets it for HTTP requests. http.timeout Type: integer Default: 30 Environment: CARGO_HTTP_TIMEOUT or HTTP_TIMEOUT Sets the timeout for each HTTP request, in seconds. http.cainfo Type: string (path) Default: none Environment: CARGO_HTTP_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify TLS certificates. If not specified, Cargo attempts to use the system certificates. http.proxy-cainfo Type: string (path) Default: falls back to http.cainfo if not set Environment: CARGO_HTTP_PROXY_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify proxy TLS certificates. http.check-revoke Type: boolean Default: true (Windows) false (all others) Environment: CARGO_HTTP_CHECK_REVOKE This determines whether or not TLS certificate revocation checks should be performed. This only works on Windows. http.ssl-version Type: string or min/max table Default: none Environment: CARGO_HTTP_SSL_VERSION This sets the minimum TLS version to use. It takes a string, with one of the possible values of "default" , "tlsv1" , "tlsv1.0" , "tlsv1.1" , "tlsv1.2" , or "tlsv1.3" . This may alternatively take a table with two keys, min and max , which each take a string value of the same kind that specifies the minimum and maximum range of TLS versions to use. The default is a minimum version of "tlsv1.0" and a max of the newest version supported on your platform, typically "tlsv1.3" . http.low-speed-limit Type: integer Default: 10 Environment: CARGO_HTTP_LOW_SPEED_LIMIT This setting controls timeout behavior for slow connections. If the average transfer speed in bytes per second is below the given value for http.timeout seconds (default 30 seconds), then the connection is considered too slow and Cargo will abort and retry. http.multiplexing Type: boolean Default: true Environment: CARGO_HTTP_MULTIPLEXING When true , Cargo will attempt to use the HTTP2 protocol with multiplexing. This allows multiple requests to use the same connection, usually improving performance when fetching multiple files. If false , Cargo will use HTTP 1.1 without pipelining. http.user-agent Type: string Default: Cargo’s version Environment: CARGO_HTTP_USER_AGENT Specifies a custom user-agent header to use. The default if not specified is a string that includes Cargo’s version. [install] The [install] table defines defaults for the cargo install command. install.root Type: string (path) Default: Cargo’s home directory Environment: CARGO_INSTALL_ROOT Sets the path to the root directory for installing executables for cargo install . Executables go into a bin directory underneath the root. To track information of installed executables, some extra files, such as .crates.toml and .crates2.json , are also created under this root. The default if not specified is Cargo’s home directory (default .cargo in your home directory). Can be overridden with the --root command-line option. [net] The [net] table controls networking configuration. net.retry Type: integer Default: 3 Environment: CARGO_NET_RETRY Number of times to retry possibly spurious network errors. net.git-fetch-with-cli Type: boolean Default: false Environment: CARGO_NET_GIT_FETCH_WITH_CLI If this is true , then Cargo will use the git executable to fetch registry indexes and git dependencies. If false , then it uses a built-in git library. Setting this to true can be helpful if you have special authentication requirements that Cargo does not support. See Git Authentication for more information about setting up git authentication. net.offline Type: boolean Default: false Environment: CARGO_NET_OFFLINE If this is true , then Cargo will avoid accessing the network, and attempt to proceed with locally cached data. If false , Cargo will access the network as needed, and generate an error if it encounters a network error. Can be overridden with the --offline command-line option. net.ssh The [net.ssh] table contains settings for SSH connections. net.ssh.known-hosts Type: array of strings Default: see description Environment: not supported The known-hosts array contains a list of SSH host keys that should be accepted as valid when connecting to an SSH server (such as for SSH git dependencies). Each entry should be a string in a format similar to OpenSSH known_hosts files. Each string should start with one or more hostnames separated by commas, a space, the key type name, a space, and the base64-encoded key. For example: [net.ssh] known-hosts = [ "example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFO4Q5T0UV0SQevair9PFwoxY9dl4pQl3u5phoqJH3cF" ] Cargo will attempt to load known hosts keys from common locations supported in OpenSSH, and will join those with any listed in a Cargo configuration file. If any matching entry has the correct key, the connection will be allowed. Cargo comes with the host keys for github.com built-in. If those ever change, you can add the new keys to the config or known_hosts file. See Git Authentication for more details. [patch] Just as you can override dependencies using [patch] in Cargo.toml , you can override them in the cargo configuration file to apply those patches to any affected build. The format is identical to the one used in Cargo.toml . Since .cargo/config.toml files are not usually checked into source control, you should prefer patching using Cargo.toml where possible to ensure that other developers can compile your crate in their own environments. Patching through cargo configuration files is generally only appropriate when the patch section is automatically generated by an external build tool. If a given dependency is patched both in a cargo configuration file and a Cargo.toml file, the patch in the configuration file is used. If multiple configuration files patch the same dependency, standard cargo configuration merging is used, which prefers the value defined closest to the current directory, with $HOME/.cargo/config.toml taking the lowest precedence. Relative path dependencies in such a [patch] section are resolved relative to the configuration file they appear in. [profile] The [profile] table can be used to globally change profile settings, and override settings specified in Cargo.toml . It has the same syntax and options as profiles specified in Cargo.toml . See the Profiles chapter for details about the options. [profile.<name>.build-override] Environment: CARGO_PROFILE_<name>_BUILD_OVERRIDE_<key> The build-override table overrides settings for build scripts, proc macros, and their dependencies. It has the same keys as a normal profile. See the overrides section for more details. [profile.<name>.package.<name>] Environment: not supported The package table overrides settings for specific packages. It has the same keys as a normal profile, minus the panic , lto , and rpath settings. See the overrides section for more details. profile.<name>.codegen-units Type: integer Default: See profile docs. Environment: CARGO_PROFILE_<name>_CODEGEN_UNITS See codegen-units . profile.<name>.debug Type: integer or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG See debug . profile.<name>.split-debuginfo Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_SPLIT_DEBUGINFO See split-debuginfo . profile.<name>.debug-assertions Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG_ASSERTIONS See debug-assertions . profile.<name>.incremental Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_INCREMENTAL See incremental . profile.<name>.lto Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_LTO See lto . profile.<name>.overflow-checks Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_OVERFLOW_CHECKS See overflow-checks . profile.<name>.opt-level Type: integer or string Default: See profile docs. Environment: CARGO_PROFILE_<name>_OPT_LEVEL See opt-level . profile.<name>.panic Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_PANIC See panic . profile.<name>.rpath Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_RPATH See rpath . profile.<name>.strip Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_STRIP See strip . [resolver] The [resolver] table overrides dependency resolution behavior for local development (e.g. excludes cargo install ). resolver.incompatible-rust-versions Type: string Default: See resolver docs Environment: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS When resolving which version of a dependency to use, select how versions with incompatible package.rust-version s are treated. Values include: allow : treat rust-version -incompatible versions like any other version fallback : only consider rust-version -incompatible versions if no other version matched Can be overridden with --ignore-rust-version CLI option Setting the dependency’s version requirement higher than any version with a compatible rust-version Specifying the version to cargo update with --precise See the resolver chapter for more details. MSRV: allow is supported on any version fallback is respected as of 1.84 [registries] The [registries] table is used for specifying additional registries . It consists of a sub-table for each named registry. registries.<name>.index Type: string (url) Default: none Environment: CARGO_REGISTRIES_<name>_INDEX Specifies the URL of the index for the registry. registries.<name>.token Type: string Default: none Environment: CARGO_REGISTRIES_<name>_TOKEN Specifies the authentication token for the given registry. This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registries.<name>.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRIES_<name>_CREDENTIAL_PROVIDER Specifies the credential provider for the given registry. If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registries.crates-io.protocol Type: string Default: "sparse" Environment: CARGO_REGISTRIES_CRATES_IO_PROTOCOL Specifies the protocol used to access crates.io. Allowed values are git or sparse . git causes Cargo to clone the entire index of all packages ever published to crates.io from https://github.com/rust-lang/crates.io-index/ . This can have performance implications due to the size of the index. sparse is a newer protocol which uses HTTPS to download only what is necessary from https://index.crates.io/ . This can result in a significant performance improvement for resolving new dependencies in most situations. More information about registry protocols may be found in the Registries chapter . [registry] The [registry] table controls the default registry used when one is not specified. registry.index This value is no longer accepted and should not be used. registry.default Type: string Default: "crates-io" Environment: CARGO_REGISTRY_DEFAULT The name of the registry (from the registries table ) to use by default for registry commands like cargo publish . Can be overridden with the --registry command-line option. registry.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRY_CREDENTIAL_PROVIDER Specifies the credential provider for crates.io . If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registry.token Type: string Default: none Environment: CARGO_REGISTRY_TOKEN Specifies the authentication token for crates.io . This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registry.global-credential-providers Type: array Default: ["cargo:token"] Environment: CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS Specifies the list of global credential providers. If credential provider is not set for a specific registry using registries.<name>.credential-provider , Cargo will use the credential providers in this list. Providers toward the end of the list have precedence. Path and arguments are split on spaces. If the path or arguments contains spaces, the credential provider should be defined in the [credential-alias] table and referenced here by its alias. See Registry Authentication for more information. [source] The [source] table defines the registry sources available. See Source Replacement for more information. It consists of a sub-table for each named source. A source should only define one kind (directory, registry, local-registry, or git). source.<name>.replace-with Type: string Default: none Environment: not supported If set, replace this source with the given named source or named registry. source.<name>.directory Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a directory source. source.<name>.registry Type: string (url) Default: none Environment: not supported Sets the URL to use for a registry source. source.<name>.local-registry Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a local registry source. source.<name>.git Type: string (url) Default: none Environment: not supported Sets the URL to use for a git repository source. source.<name>.branch Type: string Default: none Environment: not supported Sets the branch name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.tag Type: string Default: none Environment: not supported Sets the tag name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.rev Type: string Default: none Environment: not supported Sets the revision to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. [target] The [target] table is used for specifying settings for specific platform targets. It consists of a sub-table which is either a platform triple or a cfg() expression . The given values will be used if the target platform matches either the <triple> value or the <cfg> expression. [target.thumbv7m-none-eabi] linker = "arm-none-eabi-gcc" runner = "my-emulator" rustflags = ["…", "…"] [target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "my-arm-wrapper" rustflags = ["…", "…"] cfg values come from those built-in to the compiler (run rustc --print=cfg to view) and extra --cfg flags passed to rustc (such as those defined in RUSTFLAGS ). Do not try to match on debug_assertions , test , Cargo features like feature="foo" , or values set by build scripts . If using a target spec JSON file, the <triple> value is the filename stem. For example --target foo/bar.json would match [target.bar] . target.<triple>.ar This option is deprecated and unused. target.<triple>.linker Type: string (program path) Default: none Environment: CARGO_TARGET_<triple>_LINKER Specifies the linker which is passed to rustc (via -C linker ) when the <triple> is being compiled for. By default, the linker is not overridden. target.<cfg>.linker This is similar to the target linker , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.runner Type: string or array of strings ( program path with args ) Default: none Environment: CARGO_TARGET_<triple>_RUNNER If a runner is provided, executables for the target <triple> will be executed by invoking the specified runner with the actual executable passed as an argument. This applies to cargo run , cargo test and cargo bench commands. By default, compiled executables are executed directly. target.<cfg>.runner This is similar to the target runner , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.rustflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustflags for more details on the different ways to specific extra flags. target.<cfg>.rustflags This is similar to the target rustflags , but using a cfg() expression . If several <cfg> and <triple> entries match the current target, the flags are joined together. target.<triple>.rustdocflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTDOCFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustdocflags for more details on the different ways to specific extra flags. target.<triple>.<links> The links sub-table provides a way to override a build script . When specified, the build script for the given links library will not be run, and the given values will be used instead. [target.x86_64-unknown-linux-gnu.foo] rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] The [term] table controls terminal output and interaction. term.quiet Type: boolean Default: false Environment: CARGO_TERM_QUIET Controls whether or not log messages are displayed by Cargo. Specifying the --quiet flag will override and force quiet output. Specifying the --verbose flag will override and disable quiet output. term.verbose Type: boolean Default: false Environment: CARGO_TERM_VERBOSE Controls whether or not extra detailed messages are displayed by Cargo. Specifying the --quiet flag will override and disable verbose output. Specifying the --verbose flag will override and force verbose output. term.color Type: string Default: "auto" Environment: CARGO_TERM_COLOR Controls whether or not colored output is used in the terminal. Possible values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. Can be overridden with the --color command-line option. term.hyperlinks Type: bool Default: auto-detect Environment: CARGO_TERM_HYPERLINKS Controls whether or not hyperlinks are used in the terminal. term.unicode Type: bool Default: auto-detect Environment: CARGO_TERM_UNICODE Control whether output can be rendered using non-ASCII unicode characters. term.progress.when Type: string Default: "auto" Environment: CARGO_TERM_PROGRESS_WHEN Controls whether or not progress bar is shown in the terminal. Possible values: auto (default): Intelligently guess whether to show progress bar. always : Always show progress bar. never : Never show progress bar. term.progress.width Type: integer Default: none Environment: CARGO_TERM_PROGRESS_WIDTH Sets the width for progress bar. term.progress.term-integration Type: bool Default: auto-detect Environment: CARGO_TERM_PROGRESS_TERM_INTEGRATION Report progress to the terminal emulator for display in places like the task bar. | 2026-01-13T09:29:13 |
https://zh-cn.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1v_OJQfV5Zcu-cblOHFXfPicMkZBPGWKUMR8y2VtHCkhFimX0DXmuO_lS7lSOvuxvJGvNENLC3hXctnK0aEhIreuGRGjRkAY5nzNTCCWlumoLGOzuQm7GYuIQhI_WWXvHN-cB9_Akw-iZt | Facebook Facebook 邮箱或手机号 密码 忘记账户了? 创建新账户 你暂时被禁止使用此功能 你暂时被禁止使用此功能 似乎你过度使用了此功能,因此暂时被阻止,不能继续使用。 Back 中文(简体) 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 日本語 Português (Brasil) Français (France) Deutsch 注册 登录 Messenger Facebook Lite 视频 Meta Pay Meta 商店 Meta Quest Ray-Ban Meta Meta AI Meta AI 更多内容 Instagram Threads 选民信息中心 隐私政策 隐私中心 关于 创建广告 创建公共主页 开发者 招聘信息 Cookie Ad Choices 条款 帮助 联系人上传和非用户 设置 动态记录 Meta © 2026 | 2026-01-13T09:29:13 |
https://fr-fr.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1v_OJQfV5Zcu-cblOHFXfPicMkZBPGWKUMR8y2VtHCkhFimX0DXmuO_lS7lSOvuxvJGvNENLC3hXctnK0aEhIreuGRGjRkAY5nzNTCCWlumoLGOzuQm7GYuIQhI_WWXvHN-cB9_Akw-iZt | Facebook Facebook Adresse e-mail ou téléphone Mot de passe Informations de compte oubliées ? Créer un compte Cette fonction est temporairement bloquée Cette fonction est temporairement bloquée Il semble que vous ayez abusé de cette fonctionnalité en l’utilisant trop vite. Vous n’êtes plus autorisé à l’utiliser. Back Français (France) 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Deutsch S’inscrire Se connecter Messenger Facebook Lite Vidéo Meta Pay Boutique Meta Meta Quest Ray-Ban Meta Meta AI Plus de contenu Meta AI Instagram Threads Centre d’information sur les élections Politique de confidentialité Centre de confidentialité À propos Créer une publicité Créer une Page Développeurs Emplois Cookies Choisir sa publicité Conditions générales Aide Importation des contacts et non-utilisateurs Paramètres Historique d’activité Meta © 2026 | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/procedural-macros.html#derive-macro-helper-attributes | Procedural macros - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [macro .proc] Procedural macros [macro .proc .intro] Procedural macros allow creating syntax extensions as execution of a function. Procedural macros come in one of three flavors: Function-like macros - custom!(...) Derive macros - #[derive(CustomDerive)] Attribute macros - #[CustomAttribute] Procedural macros allow you to run code at compile time that operates over Rust syntax, both consuming and producing Rust syntax. You can sort of think of procedural macros as functions from an AST to another AST. [macro .proc .def] Procedural macros must be defined in the root of a crate with the crate type of proc-macro . The macros may not be used from the crate where they are defined, and can only be used when imported in another crate. Note When using Cargo, Procedural macro crates are defined with the proc-macro key in your manifest: [lib] proc-macro = true [macro .proc .result] As functions, they must either return syntax, panic, or loop endlessly. Returned syntax either replaces or adds the syntax depending on the kind of procedural macro. Panics are caught by the compiler and are turned into a compiler error. Endless loops are not caught by the compiler which hangs the compiler. Procedural macros run during compilation, and thus have the same resources that the compiler has. For example, standard input, error, and output are the same that the compiler has access to. Similarly, file access is the same. Because of this, procedural macros have the same security concerns that Cargo’s build scripts have. [macro .proc .error] Procedural macros have two ways of reporting errors. The first is to panic. The second is to emit a compile_error macro invocation. [macro .proc .proc_macro] The proc_macro crate [macro .proc .proc_macro .intro] Procedural macro crates almost always will link to the compiler-provided proc_macro crate . The proc_macro crate provides types required for writing procedural macros and facilities to make it easier. [macro .proc .proc_macro .token-stream] This crate primarily contains a TokenStream type. Procedural macros operate over token streams instead of AST nodes, which is a far more stable interface over time for both the compiler and for procedural macros to target. A token stream is roughly equivalent to Vec<TokenTree> where a TokenTree can roughly be thought of as lexical token. For example foo is an Ident token, . is a Punct token, and 1.2 is a Literal token. The TokenStream type, unlike Vec<TokenTree> , is cheap to clone. [macro .proc .proc_macro .span] All tokens have an associated Span . A Span is an opaque value that cannot be modified but can be manufactured. Span s represent an extent of source code within a program and are primarily used for error reporting. While you cannot modify a Span itself, you can always change the Span associated with any token, such as through getting a Span from another token. [macro .proc .hygiene] Procedural macro hygiene Procedural macros are unhygienic . This means they behave as if the output token stream was simply written inline to the code it’s next to. This means that it’s affected by external items and also affects external imports. Macro authors need to be careful to ensure their macros work in as many contexts as possible given this limitation. This often includes using absolute paths to items in libraries (for example, ::std::option::Option instead of Option ) or by ensuring that generated functions have names that are unlikely to clash with other functions (like __internal_foo instead of foo ). [macro .proc .function] Function-like procedural macros [macro .proc .function .intro] Function-like procedural macros are procedural macros that are invoked using the macro invocation operator ( ! ). [macro .proc .function .def] These macros are defined by a public function with the proc_macro attribute and a signature of (TokenStream) -> TokenStream . The input TokenStream is what is inside the delimiters of the macro invocation and the output TokenStream replaces the entire macro invocation. [macro .proc .function .namespace] The proc_macro attribute defines the macro in the macro namespace in the root of the crate. For example, the following macro definition ignores its input and outputs a function answer into its scope. #![crate_type = "proc-macro"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro] pub fn make_answer(_item: TokenStream) -> TokenStream { "fn answer() -> u32 { 42 }".parse().unwrap() } And then we use it in a binary crate to print “42” to standard output. extern crate proc_macro_examples; use proc_macro_examples::make_answer; make_answer!(); fn main() { println!("{}", answer()); } [macro .proc .function .invocation] Function-like procedural macros may be invoked in any macro invocation position, which includes statements , expressions , patterns , type expressions , item positions, including items in extern blocks , inherent and trait implementations , and trait definitions . [macro .proc .derive] The proc_macro_derive attribute [macro .proc .derive .intro] Applying the proc_macro_derive attribute to a function defines a derive macro that can be invoked by the derive attribute . These macros are given the token stream of a struct , enum , or union definition and can emit new items after it. They can also declare and use derive macro helper attributes . Example This derive macro ignores its input and appends tokens that define a function. #![crate_type = "proc-macro"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(AnswerFn)] pub fn derive_answer_fn(_item: TokenStream) -> TokenStream { "fn answer() -> u32 { 42 }".parse().unwrap() } To use it, we might write: extern crate proc_macro_examples; use proc_macro_examples::AnswerFn; #[derive(AnswerFn)] struct Struct; fn main() { assert_eq!(42, answer()); } [macro .proc .derive .syntax] The syntax for the proc_macro_derive attribute is: Syntax ProcMacroDeriveAttribute → proc_macro_derive ( DeriveMacroName ( , DeriveMacroAttributes ) ? , ? ) DeriveMacroName → IDENTIFIER DeriveMacroAttributes → attributes ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) Show Railroad ProcMacroDeriveAttribute proc_macro_derive ( DeriveMacroName , DeriveMacroAttributes , ) DeriveMacroName IDENTIFIER DeriveMacroAttributes attributes ( IDENTIFIER , IDENTIFIER , ) The name of the derive macro is given by DeriveMacroName . The optional attributes argument is described in macro.proc.derive.attributes . [macro .proc .derive .allowed-positions] The proc_macro_derive attribute may only be applied to a pub function with the Rust ABI defined in the root of the crate with a type of fn(TokenStream) -> TokenStream where TokenStream comes from the proc_macro crate . The function may be const and may use extern to explicitly specify the Rust ABI, but it may not use any other qualifiers (e.g. it may not be async or unsafe ). [macro .proc .derive .duplicates] The proc_macro_derive attribute may be used only once on a function. [macro .proc .derive .namespace] The proc_macro_derive attribute publicly defines the derive macro in the macro namespace in the root of the crate. [macro .proc .derive .output] The input TokenStream is the token stream of the item to which the derive attribute is applied. The output TokenStream must be a (possibly empty) set of items. These items are appended following the input item within the same module or block . [macro .proc .derive .attributes] Derive macro helper attributes [macro .proc .derive .attributes .intro] Derive macros can declare derive macro helper attributes to be used within the scope of the item to which the derive macro is applied. These attributes are inert . While their purpose is to be used by the macro that declared them, they can be seen by any macro. [macro .proc .derive .attributes .decl] A helper attribute for a derive macro is declared by adding its identifier to the attributes list in the proc_macro_derive attribute. Example This declares a helper attribute and then ignores it. #![crate_type="proc-macro"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(WithHelperAttr, attributes(helper))] pub fn derive_with_helper_attr(_item: TokenStream) -> TokenStream { TokenStream::new() } To use it, we might write: #[derive(WithHelperAttr)] struct Struct { #[helper] field: (), } [macro .proc .attribute] Attribute macros [macro .proc .attribute .intro] Attribute macros define new outer attributes which can be attached to items , including items in extern blocks , inherent and trait implementations , and trait definitions . [macro .proc .attribute .def] Attribute macros are defined by a public function with the proc_macro_attribute attribute that has a signature of (TokenStream, TokenStream) -> TokenStream . The first TokenStream is the delimited token tree following the attribute’s name, not including the outer delimiters. If the attribute is written as a bare attribute name, the attribute TokenStream is empty. The second TokenStream is the rest of the item including other attributes on the item . The returned TokenStream replaces the item with an arbitrary number of items . [macro .proc .attribute .namespace] The proc_macro_attribute attribute defines the attribute in the macro namespace in the root of the crate. For example, this attribute macro takes the input stream and returns it as is, effectively being the no-op of attributes. #![crate_type = "proc-macro"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_attribute] pub fn return_as_is(_attr: TokenStream, item: TokenStream) -> TokenStream { item } This following example shows the stringified TokenStream s that the attribute macros see. The output will show in the output of the compiler. The output is shown in the comments after the function prefixed with “out:”. // my-macro/src/lib.rs extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_attribute] pub fn show_streams(attr: TokenStream, item: TokenStream) -> TokenStream { println!("attr: \"{attr}\""); println!("item: \"{item}\""); item } // src/lib.rs extern crate my_macro; use my_macro::show_streams; // Example: Basic function #[show_streams] fn invoke1() {} // out: attr: "" // out: item: "fn invoke1() {}" // Example: Attribute with input #[show_streams(bar)] fn invoke2() {} // out: attr: "bar" // out: item: "fn invoke2() {}" // Example: Multiple tokens in the input #[show_streams(multiple => tokens)] fn invoke3() {} // out: attr: "multiple => tokens" // out: item: "fn invoke3() {}" // Example: #[show_streams { delimiters }] fn invoke4() {} // out: attr: "delimiters" // out: item: "fn invoke4() {}" [macro .proc .token] Declarative macro tokens and procedural macro tokens [macro .proc .token .intro] Declarative macro_rules macros and procedural macros use similar, but different definitions for tokens (or rather TokenTree s .) [macro .proc .token .macro_rules] Token trees in macro_rules (corresponding to tt matchers) are defined as Delimited groups ( (...) , {...} , etc) All operators supported by the language, both single-character and multi-character ones ( + , += ). Note that this set doesn’t include the single quote ' . Literals ( "string" , 1 , etc) Note that negation (e.g. -1 ) is never a part of such literal tokens, but a separate operator token. Identifiers, including keywords ( ident , r#ident , fn ) Lifetimes ( 'ident ) Metavariable substitutions in macro_rules (e.g. $my_expr in macro_rules! mac { ($my_expr: expr) => { $my_expr } } after the mac ’s expansion, which will be considered a single token tree regardless of the passed expression) [macro .proc .token .tree] Token trees in procedural macros are defined as Delimited groups ( (...) , {...} , etc) All punctuation characters used in operators supported by the language ( + , but not += ), and also the single quote ' character (typically used in lifetimes, see below for lifetime splitting and joining behavior) Literals ( "string" , 1 , etc) Negation (e.g. -1 ) is supported as a part of integer and floating point literals. Identifiers, including keywords ( ident , r#ident , fn ) [macro .proc .token .conversion .intro] Mismatches between these two definitions are accounted for when token streams are passed to and from procedural macros. Note that the conversions below may happen lazily, so they might not happen if the tokens are not actually inspected. [macro .proc .token .conversion .to-proc_macro] When passed to a proc-macro All multi-character operators are broken into single characters. Lifetimes are broken into a ' character and an identifier. The keyword metavariable $crate is passed as a single identifier. All other metavariable substitutions are represented as their underlying token streams. Such token streams may be wrapped into delimited groups ( Group ) with implicit delimiters ( Delimiter::None ) when it’s necessary for preserving parsing priorities. tt and ident substitutions are never wrapped into such groups and always represented as their underlying token trees. [macro .proc .token .conversion .from-proc_macro] When emitted from a proc macro Punctuation characters are glued into multi-character operators when applicable. Single quotes ' joined with identifiers are glued into lifetimes. Negative literals are converted into two tokens (the - and the literal) possibly wrapped into a delimited group ( Group ) with implicit delimiters ( Delimiter::None ) when it’s necessary for preserving parsing priorities. [macro .proc .token .doc-comment] Note that neither declarative nor procedural macros support doc comment tokens (e.g. /// Doc ), so they are always converted to token streams representing their equivalent #[doc = r"str"] attributes when passed to macros. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#railroad-InnerAttribute | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo.html | cargo - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo(1) NAME cargo — The Rust package manager SYNOPSIS cargo [ options ] command [ args ] cargo [ options ] --version cargo [ options ] --list cargo [ options ] --help cargo [ options ] --explain code DESCRIPTION This program is a package manager and build tool for the Rust language, available at https://rust-lang.org . COMMANDS Build Commands cargo-bench(1) Execute benchmarks of a package. cargo-build(1) Compile a package. cargo-check(1) Check a local package and all of its dependencies for errors. cargo-clean(1) Remove artifacts that Cargo has generated in the past. cargo-doc(1) Build a package’s documentation. cargo-fetch(1) Fetch dependencies of a package from the network. cargo-fix(1) Automatically fix lint warnings reported by rustc. cargo-run(1) Run a binary or example of the local package. cargo-rustc(1) Compile a package, and pass extra options to the compiler. cargo-rustdoc(1) Build a package’s documentation, using specified custom flags. cargo-test(1) Execute unit and integration tests of a package. Manifest Commands cargo-add(1) Add dependencies to a Cargo.toml manifest file. cargo-generate-lockfile(1) Generate Cargo.lock for a project. cargo-info(1) Display information about a package in the registry. Default registry is crates.io. cargo-locate-project(1) Print a JSON representation of a Cargo.toml file’s location. cargo-metadata(1) Output the resolved dependencies of a package in machine-readable format. cargo-pkgid(1) Print a fully qualified package specification. cargo-remove(1) Remove dependencies from a Cargo.toml manifest file. cargo-tree(1) Display a tree visualization of a dependency graph. cargo-update(1) Update dependencies as recorded in the local lock file. cargo-vendor(1) Vendor all dependencies locally. Package Commands cargo-init(1) Create a new Cargo package in an existing directory. cargo-install(1) Build and install a Rust binary. cargo-new(1) Create a new Cargo package. cargo-search(1) Search packages in crates.io. cargo-uninstall(1) Remove a Rust binary. Publishing Commands cargo-login(1) Save an API token from the registry locally. cargo-logout(1) Remove an API token from the registry locally. cargo-owner(1) Manage the owners of a crate on the registry. cargo-package(1) Assemble the local package into a distributable tarball. cargo-publish(1) Upload a package to the registry. cargo-yank(1) Remove a pushed crate from the index. General Commands cargo-help(1) Display help information about Cargo. cargo-version(1) Show version information. OPTIONS Special Options -V --version Print version info and exit. If used with --verbose , prints extra information. --list List all installed Cargo subcommands. If used with --verbose , prints extra information. --explain code Run rustc --explain CODE which will print out a detailed explanation of an error message (for example, E0004 ). Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Manifest Options --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. FILES ~/.cargo/ Default location for Cargo’s “home” directory where it stores various files. The location can be changed with the CARGO_HOME environment variable. $CARGO_HOME/bin/ Binaries installed by cargo-install(1) will be located here. If using rustup , executables distributed with Rust are also located here. $CARGO_HOME/config.toml The global configuration file. See the reference for more information about configuration files. .cargo/config.toml Cargo automatically searches for a file named .cargo/config.toml in the current directory, and all parent directories. These configuration files will be merged with the global configuration file. $CARGO_HOME/credentials.toml Private authentication information for logging in to a registry. $CARGO_HOME/registry/ This directory contains cached downloads of the registry index and any downloaded dependencies. $CARGO_HOME/git/ This directory contains cached downloads of git dependencies. Please note that the internal structure of the $CARGO_HOME directory is not stable yet and may be subject to change. EXAMPLES Build a local package and all of its dependencies: cargo build Build a package with optimizations: cargo build --release Run tests for a cross-compiled target: cargo test --target i686-unknown-linux-gnu Create a new package that builds an executable: cargo new foobar Create a package in the current directory: mkdir foo && cd foo cargo init . Learn about a command’s options and usage: cargo help clean BUGS See https://github.com/rust-lang/cargo/issues for issues. SEE ALSO rustc(1) , rustdoc(1) | 2026-01-13T09:29:13 |
https://es-la.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1v_OJQfV5Zcu-cblOHFXfPicMkZBPGWKUMR8y2VtHCkhFimX0DXmuO_lS7lSOvuxvJGvNENLC3hXctnK0aEhIreuGRGjRkAY5nzNTCCWlumoLGOzuQm7GYuIQhI_WWXvHN-cB9_Akw-iZt | Facebook Facebook Correo o teléfono Contraseña ¿Olvidaste tu cuenta? Crear cuenta nueva Se te bloqueó temporalmente Se te bloqueó temporalmente Parece que hiciste un uso indebido de esta función al ir muy rápido. Se te bloqueó su uso temporalmente. Back Español 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch Registrarte Iniciar sesión Messenger Facebook Lite Video Meta Pay Tienda de Meta Meta Quest Ray-Ban Meta Meta AI Más contenido de Meta AI Instagram Threads Centro de información de votación Política de privacidad Centro de privacidad Información Crear anuncio Crear página Desarrolladores Empleo Cookies Opciones de anuncios Condiciones Ayuda Importación de contactos y no usuarios Configuración Registro de actividad Meta © 2026 | 2026-01-13T09:29:13 |
https://www.linkedin.com/legal/cookie-policy?session_redirect=https%3A%2F%2Fwww%2Elinkedin%2Ecom%2Fposts%2Fryanheinrichs_userexperience-webdesign-uiux-activity-7408999842783395840--gY1&trk=registration-frontend_join-form-cookie-policy | Cookie Policy | LinkedIn Skip to main content User Agreement Summary of User Agreement Privacy Policy Professional Community Policies Cookie Policy Copyright Policy Regional Info EU Notice California Privacy Disclosure U.S. State Privacy Laws User Agreement Summary of User Agreement Privacy Policy Professional Community Policies Cookie Policy Copyright Policy Regional Info EU Notice California Privacy Disclosure U.S. State Privacy Laws Cookie Policy Effective on June 3, 2022 At LinkedIn, we believe in being clear and open about how we collect and use data related to you. This Cookie Policy applies to any LinkedIn product or service that links to this policy or incorporates it by reference. We use cookies and similar technologies such as pixels, local storage and mobile ad IDs (collectively referred to in this policy as “cookies”) to collect and use data as part of our Services, as defined in our Privacy Policy (“Services”) and which includes our sites, communications, mobile applications and off-site Services, such as our ad services and the “Apply with LinkedIn” and “Share with LinkedIn” plugins or tags. In the spirit of transparency, this policy provides detailed information about how and when we use these technologies. By continuing to visit or use our Services, you are agreeing to the use of cookies and similar technologies for the purposes described in this policy. What technologies are used? ENTER A SUMMARY Type of technology Description Cookies A cookie is a small file placed onto your device that enables LinkedIn features and functionality. Any browser visiting our sites may receive cookies from us or cookies from third parties such as our customers, partners or service providers. We or third parties may also place cookies in your browser when you visit non-LinkedIn sites that display ads or that host our plugins or tags . We use two types of cookies: persistent cookies and session cookies. A persistent cookie lasts beyond the current session and is used for many purposes, such as recognizing you as an existing user, so it’s easier to return to LinkedIn and interact with our Services without signing in again. Since a persistent cookie stays in your browser, it will be read by LinkedIn when you return to one of our sites or visit a third party site that uses our Services. Session cookies last only as long as the session (usually the current visit to a website or a browser session). Pixels A pixel is a tiny image that may be embedded within web pages and emails, requiring a call (which provides device and visit information) to our servers in order for the pixel to be rendered in those web pages and emails. We use pixels to learn more about your interactions with email content or web content, such as whether you interacted with ads or posts. Pixels can also enable us and third parties to place cookies on your browser. Local storage Local storage enables a website or application to store information locally on your device(s). Local storage may be used to improve the LinkedIn experience, for example, by enabling features, remembering your preferences and speeding up site functionality. Other similar technologies We also use other tracking technologies, such as mobile advertising IDs and tags for similar purposes as described in this Cookie Policy. References to similar technologies in this policy includes pixels, local storage, and other tracking technologies. Our cookie tables lists cookies and similar technologies that are used as part of our Services. Please note that the names of cookies and similar technologies may change over time. What are these technologies used for? Below we describe the purposes for which we use these technologies. ENTER SUMMARY Purpose Description Authentication We use cookies and similar technologies to recognize you when you visit our Services. If you’re signed into LinkedIn, these technologies help us show you the right information and personalize your experience in line with your settings. For example, cookies enable LinkedIn to identify you and verify your account. Security We use cookies and similar technologies to make your interactions with our Services faster and more secure. For example, we use cookies to enable and support our security features, keep your account safe and to help us detect malicious activity and violations of our User Agreement. Preferences, features and services We use cookies and similar technologies to enable the functionality of our Services, such as helping you to fill out forms on our Services more easily and providing you with features, insights and customized content in conjunction with our plugins. We also use these technologies to remember information about your browser and your preferences. For example, cookies can tell us which language you prefer and what your communications preferences are. We may also use local storage to speed up site functionality. Customized content We use cookies and similar technologies to customize your experience on our Services. For example, we may use cookies to remember previous searches so that when you return to our services, we can offer additional information that relates to your previous search. Plugins on and off LinkedIn We use cookies and similar technologies to enable LinkedIn plugins both on and off the LinkedIn sites. For example, our plugins, including the "Apply with LinkedIn" button or the "Share" button may be found on LinkedIn or third-party sites, such as the sites of our customers and partners. Our plugins use cookies and other technologies to provide analytics and recognize you on LinkedIn and third-party sites. If you interact with a plugin (for instance, by clicking "Apply"), the plugin will use cookies to identify you and initiate your request to apply. You can learn more about plugins in our Privacy Policy . Advertising Cookies and similar technologies help us show relevant advertising to you more effectively, both on and off our Services and to measure the performance of such ads. We use these technologies to learn whether content has been shown to you or whether someone who was presented with an ad later came back and took an action (e.g., downloaded a white paper or made a purchase) on another site. Similarly, our partners or service providers may use these technologies to determine whether we've shown an ad or a post and how it performed or provide us with information about how you interact with ads. We may also work with our customers and partners to show you an ad on or off LinkedIn, such as after you’ve visited a customer’s or partner’s site or application. These technologies help us provide aggregated information to our customers and partners. For further information regarding the use of cookies for advertising purposes, please see Sections 1.4 and 2.4 of the Privacy Policy . As noted in Section 1.4 of our Privacy Policy, outside Designated Countries , we also collect (or rely on others who collect) information about your device where you have not engaged with our Services (e.g., ad ID, IP address, operating system and browser information) so we can provide our Members with relevant ads and better understand their effectiveness. For further information, please see Section 1.4 of the Privacy Policy . Analytics and research Cookies and similar technologies help us learn more about how well our Services and plugins perform in different locations. We or our service providers use these technologies to understand, improve, and research products, features and services, including as you navigate through our sites or when you access LinkedIn from other sites, applications or devices. We or our service providers, use these technologies to determine and measure the performance of ads or posts on and off LinkedIn and to learn whether you have interacted with our websites, content or emails and provide analytics based on those interactions. We also use these technologies to provide aggregated information to our customers and partners as part of our Services. If you are a LinkedIn member but logged out of your account on a browser, LinkedIn may still continue to log your interaction with our Services on that browser until the expiration of the cookie in order to generate usage analytics for our Services. We may share these analytics in aggregate form with our customers. What third parties use these technologies in connection with our Services? Third parties such as our customers, partners and service providers may use cookies in connection with our Services. For example, third parties may use cookies in their LinkedIn pages, job posts and their advertisements on and off LinkedIn for their own marketing purposes. For an illustration, please visit LinkedIn’s Help Center . Third parties may also use cookies in connection with our off-site Services, such as LinkedIn ad services. Third parties may use cookies to help us to provide our Services. We may also work with third parties for our own marketing purposes and to enable us to analyze and research our Services. Your Choices You have choices on how LinkedIn uses cookies and similar technologies. Please note that if you limit the ability of LinkedIn to set cookies and similar technologies, you may worsen your overall user experience, since it may no longer be personalized to you. It may also stop you from saving customized settings like login information. Opt out of targeted advertising As described in Section 2.4 of the Privacy Policy , you have choices regarding the personalized ads you may see. LinkedIn Members can adjust their settings here . Visitor controls can be found here . Some mobile device operating systems such as Android provide the ability to control the use of mobile advertising IDs for ads personalization. You can learn how to use these controls by visiting the manufacturer’s website. We do not use iOS mobile advertising IDs for targeted advertising. Browser Controls Most browsers allow you to control cookies through their settings, which may be adapted to reflect your consent to the use of cookies. Further, most browsers also enable you to review and erase cookies, including LinkedIn cookies. To learn more about browser controls, please consult the documentation that your browser manufacturer provides. What is Do Not Track (DNT)? DNT is a concept that has been promoted by regulatory agencies such as the U.S. Federal Trade Commission (FTC), for the Internet industry to develop and implement a mechanism for allowing Internet users to control the tracking of their online activities across websites by using browser settings. As such, LinkedIn does not generally respond to “do not track” signals. Other helpful resources To learn more about advertisers’ use of cookies, please visit the following links: Internet Advertising Bureau (US) European Interactive Digital Advertising Alliance (EU) Internet Advertising Bureau (EU) LinkedIn © 2026 About Accessibility User Agreement Privacy Policy Cookie Policy Copyright Policy Brand Policy Guest Controls Community Guidelines العربية (Arabic) বাংলা (Bangla) Čeština (Czech) Dansk (Danish) Deutsch (German) Ελληνικά (Greek) English (English) Español (Spanish) فارسی (Persian) Suomi (Finnish) Français (French) हिंदी (Hindi) Magyar (Hungarian) Bahasa Indonesia (Indonesian) Italiano (Italian) עברית (Hebrew) 日本語 (Japanese) 한국어 (Korean) मराठी (Marathi) Bahasa Malaysia (Malay) Nederlands (Dutch) Norsk (Norwegian) ਪੰਜਾਬੀ (Punjabi) Polski (Polish) Português (Portuguese) Română (Romanian) Русский (Russian) Svenska (Swedish) తెలుగు (Telugu) ภาษาไทย (Thai) Tagalog (Tagalog) Türkçe (Turkish) Українська (Ukrainian) Tiếng Việt (Vietnamese) 简体中文 (Chinese (Simplified)) 正體中文 (Chinese (Traditional)) Language | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#grammar-MetaItemInner | Attributes - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [attributes] Attributes [attributes .syntax] Syntax InnerAttribute → # ! [ Attr ] OuterAttribute → # [ Attr ] Attr → SimplePath AttrInput ? | unsafe ( SimplePath AttrInput ? ) AttrInput → DelimTokenTree | = Expression Show Railroad InnerAttribute # ! [ Attr ] OuterAttribute # [ Attr ] Attr SimplePath AttrInput unsafe ( SimplePath AttrInput ) AttrInput DelimTokenTree = Expression [attributes .intro] An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335 , with the syntax coming from ECMA-334 (C#). [attributes .inner] Inner attributes , written with a bang ( ! ) after the hash ( # ), apply to the item that the attribute is declared within. Outer attributes , written without the bang after the hash, apply to the thing that follows the attribute. [attributes .input] The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression. See the meta item syntax below for more details. [attributes .safety] An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in unsafe(..) , e.g. #[unsafe(no_mangle)] . The following attributes are unsafe: export_name link_section naked no_mangle [attributes .kind] Attributes can be classified into the following kinds: Built-in attributes Proc macro attributes Derive macro helper attributes Tool attributes [attributes .allowed-position] Attributes may be applied to many things in the language: All item declarations accept outer attributes while external blocks , functions , implementations , and modules accept inner attributes. Most statements accept outer attributes (see Expression Attributes for limitations on expression statements). Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression. Enum variants and struct and union fields accept outer attributes. Match expression arms accept outer attributes. Generic lifetime or type parameter accept outer attributes. Expressions accept outer attributes in limited situations, see Expression Attributes for details. Function , closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with ... in function pointers and external blocks . Some examples of attributes: #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } [attributes .meta] Meta item attribute syntax [attributes .meta .intro] A “meta item” is the syntax used for the Attr rule by most built-in attributes . It has the following grammar: [attributes .meta .syntax] Syntax MetaItem → SimplePath | SimplePath = Expression | SimplePath ( MetaSeq ? ) MetaSeq → MetaItemInner ( , MetaItemInner ) * , ? MetaItemInner → MetaItem | Expression Show Railroad MetaItem SimplePath SimplePath = Expression SimplePath ( MetaSeq ) MetaSeq MetaItemInner , MetaItemInner , MetaItemInner MetaItem Expression [attributes .meta .literal-expr] Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. [attributes .meta .order] Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the Serialize proc-macro first, which must preserve the include_str! call in order for it to be expanded: #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } [attributes .meta .order-macro] Additionally, macros in attributes will be expanded only after all other attributes applied to the item: #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} [attributes .meta .builtin] Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: [attributes .meta .builtin .syntax] Syntax MetaWord → IDENTIFIER MetaNameValueStr → IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL ) MetaListPaths → IDENTIFIER ( ( SimplePath ( , SimplePath ) * , ? ) ? ) MetaListIdents → IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER ) * , ? ) ? ) MetaListNameValueStr → IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr ) * , ? ) ? ) Show Railroad MetaWord IDENTIFIER MetaNameValueStr IDENTIFIER = STRING_LITERAL RAW_STRING_LITERAL MetaListPaths IDENTIFIER ( SimplePath , SimplePath , ) MetaListIdents IDENTIFIER ( IDENTIFIER , IDENTIFIER , ) MetaListNameValueStr IDENTIFIER ( MetaNameValueStr , MetaNameValueStr , ) Some examples of meta items are: Style Example MetaWord no_std MetaNameValueStr doc = "example" MetaListPaths allow(unused, clippy::inline_always) MetaListIdents macro_use(foo, bar) MetaListNameValueStr link(name = "CoreFoundation", kind = "framework") [attributes .activity] Active and inert attributes [attributes .activity .intro] An attribute is either active or inert. During attribute processing, active attributes remove themselves from the thing they are on while inert attributes stay on. The cfg and cfg_attr attributes are active. Attribute macros are active. All other attributes are inert. [attributes .tool] Tool attributes [attributes .tool .intro] The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude . The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. [attributes .tool .ignored] When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. [attributes .tool .prelude] Tool attributes are not available if the no_implicit_prelude attribute is used. #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } Note rustc currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri” and “rust_analyzer”. [attributes .builtin] Built-in attributes index The following is an index of all built-in attributes. Conditional compilation cfg — Controls conditional compilation. cfg_attr — Conditionally includes attributes. Testing test — Marks a function as a test. ignore — Disables a test function. should_panic — Indicates a test should generate a panic. Derive derive — Automatic trait implementations. automatically_derived — Marker for implementations created by derive . Macros macro_export — Exports a macro_rules macro for cross-crate usage. macro_use — Expands macro visibility, or imports macros from other crates. proc_macro — Defines a function-like macro. proc_macro_derive — Defines a derive macro. proc_macro_attribute — Defines an attribute macro. Diagnostics allow , expect , warn , deny , forbid — Alters the default lint level. deprecated — Generates deprecation notices. must_use — Generates a lint for unused values. diagnostic::on_unimplemented — Hints the compiler to emit a certain error message if a trait is not implemented. diagnostic::do_not_recommend — Hints the compiler to not show a certain trait impl in error messages. ABI, linking, symbols, and FFI link — Specifies a native library to link with an extern block. link_name — Specifies the name of the symbol for functions or statics in an extern block. link_ordinal — Specifies the ordinal of the symbol for functions or statics in an extern block. no_link — Prevents linking an extern crate. repr — Controls type layout. crate_type — Specifies the type of crate (library, executable, etc.). no_main — Disables emitting the main symbol. export_name — Specifies the exported symbol name for a function or static. link_section — Specifies the section of an object file to use for a function or static. no_mangle — Disables symbol name encoding. used — Forces the compiler to keep a static item in the output object file. crate_name — Specifies the crate name. Code generation inline — Hint to inline code. cold — Hint that a function is unlikely to be called. naked — Prevent the compiler from emitting a function prologue and epilogue. no_builtins — Disables use of certain built-in functions. target_feature — Configure platform-specific code generation. track_caller — Pass the parent call location to std::panic::Location::caller() . instruction_set — Specify the instruction set used to generate a functions code Documentation doc — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into doc attributes. Preludes no_std — Removes std from the prelude. no_implicit_prelude — Disables prelude lookups within a module. Modules path — Specifies the filename for a module. Limits recursion_limit — Sets the maximum recursion limit for certain compile-time operations. type_length_limit — Sets the maximum size of a polymorphic type. Runtime panic_handler — Sets the function to handle panics. global_allocator — Sets the global memory allocator. windows_subsystem — Specifies the windows subsystem to link with. Features feature — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in rustc . Type System non_exhaustive — Indicate that a type will have more fields/variants added in future. Debugger debugger_visualizer — Embeds a file that specifies debugger output for a type. collapse_debuginfo — Controls how macro invocations are encoded in debuginfo. | 2026-01-13T09:29:13 |
https://id-id.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1v_OJQfV5Zcu-cblOHFXfPicMkZBPGWKUMR8y2VtHCkhFimX0DXmuO_lS7lSOvuxvJGvNENLC3hXctnK0aEhIreuGRGjRkAY5nzNTCCWlumoLGOzuQm7GYuIQhI_WWXvHN-cB9_Akw-iZt | Facebook Facebook Email atau telepon Kata Sandi Lupa akun? Buat Akun Baru Anda Diblokir Sementara Anda Diblokir Sementara Sepertinya Anda menyalahgunakan fitur ini dengan menggunakannya terlalu cepat. Anda dilarang menggunakan fitur ini untuk sementara. Back Bahasa Indonesia 한국어 English (US) Tiếng Việt ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch Daftar Masuk Messenger Facebook Lite Video Meta Pay Meta Store Meta Quest Ray-Ban Meta Meta AI Konten Meta AI lainnya Instagram Threads Pusat Informasi Pemilu Kebijakan Privasi Pusat Privasi Tentang Buat Iklan Buat Halaman Developer Karier Cookie Pilihan Iklan Ketentuan Bantuan Pengunggahan Kontak & Non-Pengguna Pengaturan Log aktivitas Meta © 2026 | 2026-01-13T09:29:13 |
https://th-th.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1v_OJQfV5Zcu-cblOHFXfPicMkZBPGWKUMR8y2VtHCkhFimX0DXmuO_lS7lSOvuxvJGvNENLC3hXctnK0aEhIreuGRGjRkAY5nzNTCCWlumoLGOzuQm7GYuIQhI_WWXvHN-cB9_Akw-iZt | Facebook Facebook อีเมลหรือโทรศัพท์ รหัสผ่าน ลืมบัญชีใช่หรือไม่ สร้างบัญชีใหม่ คุณถูกบล็อกชั่วคราว คุณถูกบล็อกชั่วคราว ดูเหมือนว่าคุณจะใช้คุณสมบัตินี้ในทางที่ผิดโดยการใช้เร็วเกินไป คุณถูกบล็อกจากการใช้โดยชั่วคราว Back ภาษาไทย 한국어 English (US) Tiếng Việt Bahasa Indonesia Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch สมัคร เข้าสู่ระบบ Messenger Facebook Lite วิดีโอ Meta Pay Meta Store Meta Quest Ray-Ban Meta Meta AI เนื้อหาเพิ่มเติมจาก Meta AI Instagram Threads ศูนย์ข้อมูลการลงคะแนนเสียง นโยบายความเป็นส่วนตัว ศูนย์ความเป็นส่วนตัว เกี่ยวกับ สร้างโฆษณา สร้างเพจ ผู้พัฒนา ร่วมงานกับ Facebook คุกกี้ ตัวเลือกโฆษณา เงื่อนไข ความช่วยเหลือ การอัพโหลดผู้ติดต่อและผู้ที่ไม่ได้ใช้บริการ การตั้งค่า บันทึกกิจกรรม Meta © 2026 | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#see-also | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---workspace | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package--j | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#examples | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---package | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#conversions-use-the-standard-traits-from-asref-asmut-c-conv-traits | Interoperability - Rust API Guidelines About Checklist 1. Naming 2. Interoperability 3. Macros 4. Documentation 5. Predictability 6. Flexibility 7. Type safety 8. Dependability 9. Debuggability 10. Future proofing 11. Necessities External links Light (default) Rust Coal Navy Ayu Rust API Guidelines Interoperability Types eagerly implement common traits (C-COMMON-TRAITS) Rust's trait system does not allow orphans : roughly, every impl must live either in the crate that defines the trait or the implementing type. Consequently, crates that define new types should eagerly implement all applicable, common traits. To see why, consider the following situation: Crate std defines trait Display . Crate url defines type Url , without implementing Display . Crate webapp imports from both std and url , There is no way for webapp to add Display to Url , since it defines neither. (Note: the newtype pattern can provide an efficient, but inconvenient workaround.) The most important common traits to implement from std are: Copy Clone Eq PartialEq Ord PartialOrd Hash Debug Display Default Note that it is common and expected for types to implement both Default and an empty new constructor. new is the constructor convention in Rust, and users expect it to exist, so if it is reasonable for the basic constructor to take no arguments, then it should, even if it is functionally identical to default . Conversions use the standard traits From , AsRef , AsMut (C-CONV-TRAITS) The following conversion traits should be implemented where it makes sense: From TryFrom AsRef AsMut The following conversion traits should never be implemented: Into TryInto These traits have a blanket impl based on From and TryFrom . Implement those instead. Examples from the standard library From<u16> is implemented for u32 because a smaller integer can always be converted to a bigger integer. From<u32> is not implemented for u16 because the conversion may not be possible if the integer is too big. TryFrom<u32> is implemented for u16 and returns an error if the integer is too big to fit in u16 . From<Ipv6Addr> is implemented for IpAddr , which is a type that can represent both v4 and v6 IP addresses. Collections implement FromIterator and Extend (C-COLLECT) FromIterator and Extend enable collections to be used conveniently with the following iterator methods: Iterator::collect Iterator::partition Iterator::unzip FromIterator is for creating a new collection containing items from an iterator, and Extend is for adding items from an iterator onto an existing collection. Examples from the standard library Vec<T> implements both FromIterator<T> and Extend<T> . Data structures implement Serde's Serialize , Deserialize (C-SERDE) Types that play the role of a data structure should implement Serialize and Deserialize . There is a continuum of types between things that are clearly a data structure and things that are clearly not, with gray area in between. LinkedHashMap and IpAddr are data structures. It would be completely reasonable for somebody to want to read in a LinkedHashMap or IpAddr from a JSON file, or send one over IPC to another process. LittleEndian is not a data structure. It is a marker used by the byteorder crate to optimize at compile time for bytes in a particular order, and in fact an instance of LittleEndian can never exist at runtime. So these are clear-cut examples; the #rust or #serde IRC channels can help assess more ambiguous cases if necessary. If a crate does not already depend on Serde for other reasons, it may wish to gate Serde impls behind a Cargo cfg. This way downstream libraries only need to pay the cost of compiling Serde if they need those impls to exist. For consistency with other Serde-based libraries, the name of the Cargo cfg should be simply "serde" . Do not use a different name for the cfg like "serde_impls" or "serde_serialization" . The canonical implementation looks like this when not using derive: [dependencies] serde = { version = "1.0", optional = true } #![allow(unused)] fn main() { pub struct T { /* ... */ } #[cfg(feature = "serde")] impl Serialize for T { /* ... */ } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for T { /* ... */ } } And when using derive: [dependencies] serde = { version = "1.0", optional = true, features = ["derive"] } #![allow(unused)] fn main() { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct T { /* ... */ } } Types are Send and Sync where possible (C-SEND-SYNC) Send and Sync are automatically implemented when the compiler determines it is appropriate. In types that manipulate raw pointers, be vigilant that the Send and Sync status of your type accurately reflects its thread safety characteristics. Tests like the following can help catch unintentional regressions in whether the type implements Send or Sync . #![allow(unused)] fn main() { #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<MyStrangeType>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<MyStrangeType>(); } } Error types are meaningful and well-behaved (C-GOOD-ERR) An error type is any type E used in a Result<T, E> returned by any public function of your crate. Error types should always implement the std::error::Error trait which is the mechanism by which error handling libraries like error-chain abstract over different types of errors, and which allows the error to be used as the source() of another error. Additionally, error types should implement the Send and Sync traits. An error that is not Send cannot be returned by a thread run with thread::spawn . An error that is not Sync cannot be passed across threads using an Arc . These are common requirements for basic error handling in a multithreaded application. Send and Sync are also important for being able to package a custom error into an IO error using std::io::Error::new , which requires a trait bound of Error + Send + Sync . One place to be vigilant about this guideline is in functions that return Error trait objects, for example reqwest::Error::get_ref . Typically Error + Send + Sync + 'static will be the most useful for callers. The addition of 'static allows the trait object to be used with Error::downcast_ref . Never use () as an error type, even where there is no useful additional information for the error to carry. () does not implement Error so it cannot be used with error handling libraries like error-chain . () does not implement Display so a user would need to write an error message of their own if they want to fail because of the error. () has an unhelpful Debug representation for users that decide to unwrap() the error. It would not be semantically meaningful for a downstream library to implement From<()> for their error type, so () as an error type cannot be used with the ? operator. Instead, define a meaningful error type specific to your crate or to the individual function. Provide appropriate Error and Display impls. If there is no useful information for the error to carry, it can be implemented as a unit struct. #![allow(unused)] fn main() { use std::error::Error; use std::fmt::Display; // Instead of this... fn do_the_thing() -> Result<Wow, ()> // Prefer this... fn do_the_thing() -> Result<Wow, DoError> #[derive(Debug)] struct DoError; impl Display for DoError { /* ... */ } impl Error for DoError { /* ... */ } } The error message given by the Display representation of an error type should be lowercase without trailing punctuation, and typically concise. Error::description() should not be implemented. It has been deprecated and users should always use Display instead of description() to print the error. Examples from the standard library ParseBoolError is returned when failing to parse a bool from a string. Examples of error messages "unexpected end of file" "provided string was not `true` or `false`" "invalid IP address syntax" "second time provided was later than self" "invalid UTF-8 sequence of {} bytes from index {}" "environment variable was not valid unicode: {:?}" Binary number types provide Hex , Octal , Binary formatting (C-NUM-FMT) std::fmt::UpperHex std::fmt::LowerHex std::fmt::Octal std::fmt::Binary These traits control the representation of a type under the {:X} , {:x} , {:o} , and {:b} format specifiers. Implement these traits for any number type on which you would consider doing bitwise manipulations like | or & . This is especially appropriate for bitflag types. Numeric quantity types like struct Nanoseconds(u64) probably do not need these. Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE) The standard library contains these two impls: #![allow(unused)] fn main() { impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ } impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ } } That means any function that accepts R: Read or W: Write generic parameters by value can be called with a mut reference if necessary. In the documentation of such functions, briefly remind users that a mut reference can be passed. New Rust users often struggle with this. They may have opened a file and want to read multiple pieces of data out of it, but the function to read one piece consumes the reader by value, so they are stuck. The solution would be to leverage one of the above impls and pass &mut f instead of f as the reader parameter. Examples flate2::read::GzDecoder::new flate2::write::GzEncoder::new serde_json::from_reader serde_json::to_writer | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#binary-number-types-provide-hex-octal-binary-formatting-c-num-fmt | Interoperability - Rust API Guidelines About Checklist 1. Naming 2. Interoperability 3. Macros 4. Documentation 5. Predictability 6. Flexibility 7. Type safety 8. Dependability 9. Debuggability 10. Future proofing 11. Necessities External links Light (default) Rust Coal Navy Ayu Rust API Guidelines Interoperability Types eagerly implement common traits (C-COMMON-TRAITS) Rust's trait system does not allow orphans : roughly, every impl must live either in the crate that defines the trait or the implementing type. Consequently, crates that define new types should eagerly implement all applicable, common traits. To see why, consider the following situation: Crate std defines trait Display . Crate url defines type Url , without implementing Display . Crate webapp imports from both std and url , There is no way for webapp to add Display to Url , since it defines neither. (Note: the newtype pattern can provide an efficient, but inconvenient workaround.) The most important common traits to implement from std are: Copy Clone Eq PartialEq Ord PartialOrd Hash Debug Display Default Note that it is common and expected for types to implement both Default and an empty new constructor. new is the constructor convention in Rust, and users expect it to exist, so if it is reasonable for the basic constructor to take no arguments, then it should, even if it is functionally identical to default . Conversions use the standard traits From , AsRef , AsMut (C-CONV-TRAITS) The following conversion traits should be implemented where it makes sense: From TryFrom AsRef AsMut The following conversion traits should never be implemented: Into TryInto These traits have a blanket impl based on From and TryFrom . Implement those instead. Examples from the standard library From<u16> is implemented for u32 because a smaller integer can always be converted to a bigger integer. From<u32> is not implemented for u16 because the conversion may not be possible if the integer is too big. TryFrom<u32> is implemented for u16 and returns an error if the integer is too big to fit in u16 . From<Ipv6Addr> is implemented for IpAddr , which is a type that can represent both v4 and v6 IP addresses. Collections implement FromIterator and Extend (C-COLLECT) FromIterator and Extend enable collections to be used conveniently with the following iterator methods: Iterator::collect Iterator::partition Iterator::unzip FromIterator is for creating a new collection containing items from an iterator, and Extend is for adding items from an iterator onto an existing collection. Examples from the standard library Vec<T> implements both FromIterator<T> and Extend<T> . Data structures implement Serde's Serialize , Deserialize (C-SERDE) Types that play the role of a data structure should implement Serialize and Deserialize . There is a continuum of types between things that are clearly a data structure and things that are clearly not, with gray area in between. LinkedHashMap and IpAddr are data structures. It would be completely reasonable for somebody to want to read in a LinkedHashMap or IpAddr from a JSON file, or send one over IPC to another process. LittleEndian is not a data structure. It is a marker used by the byteorder crate to optimize at compile time for bytes in a particular order, and in fact an instance of LittleEndian can never exist at runtime. So these are clear-cut examples; the #rust or #serde IRC channels can help assess more ambiguous cases if necessary. If a crate does not already depend on Serde for other reasons, it may wish to gate Serde impls behind a Cargo cfg. This way downstream libraries only need to pay the cost of compiling Serde if they need those impls to exist. For consistency with other Serde-based libraries, the name of the Cargo cfg should be simply "serde" . Do not use a different name for the cfg like "serde_impls" or "serde_serialization" . The canonical implementation looks like this when not using derive: [dependencies] serde = { version = "1.0", optional = true } #![allow(unused)] fn main() { pub struct T { /* ... */ } #[cfg(feature = "serde")] impl Serialize for T { /* ... */ } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for T { /* ... */ } } And when using derive: [dependencies] serde = { version = "1.0", optional = true, features = ["derive"] } #![allow(unused)] fn main() { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct T { /* ... */ } } Types are Send and Sync where possible (C-SEND-SYNC) Send and Sync are automatically implemented when the compiler determines it is appropriate. In types that manipulate raw pointers, be vigilant that the Send and Sync status of your type accurately reflects its thread safety characteristics. Tests like the following can help catch unintentional regressions in whether the type implements Send or Sync . #![allow(unused)] fn main() { #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<MyStrangeType>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<MyStrangeType>(); } } Error types are meaningful and well-behaved (C-GOOD-ERR) An error type is any type E used in a Result<T, E> returned by any public function of your crate. Error types should always implement the std::error::Error trait which is the mechanism by which error handling libraries like error-chain abstract over different types of errors, and which allows the error to be used as the source() of another error. Additionally, error types should implement the Send and Sync traits. An error that is not Send cannot be returned by a thread run with thread::spawn . An error that is not Sync cannot be passed across threads using an Arc . These are common requirements for basic error handling in a multithreaded application. Send and Sync are also important for being able to package a custom error into an IO error using std::io::Error::new , which requires a trait bound of Error + Send + Sync . One place to be vigilant about this guideline is in functions that return Error trait objects, for example reqwest::Error::get_ref . Typically Error + Send + Sync + 'static will be the most useful for callers. The addition of 'static allows the trait object to be used with Error::downcast_ref . Never use () as an error type, even where there is no useful additional information for the error to carry. () does not implement Error so it cannot be used with error handling libraries like error-chain . () does not implement Display so a user would need to write an error message of their own if they want to fail because of the error. () has an unhelpful Debug representation for users that decide to unwrap() the error. It would not be semantically meaningful for a downstream library to implement From<()> for their error type, so () as an error type cannot be used with the ? operator. Instead, define a meaningful error type specific to your crate or to the individual function. Provide appropriate Error and Display impls. If there is no useful information for the error to carry, it can be implemented as a unit struct. #![allow(unused)] fn main() { use std::error::Error; use std::fmt::Display; // Instead of this... fn do_the_thing() -> Result<Wow, ()> // Prefer this... fn do_the_thing() -> Result<Wow, DoError> #[derive(Debug)] struct DoError; impl Display for DoError { /* ... */ } impl Error for DoError { /* ... */ } } The error message given by the Display representation of an error type should be lowercase without trailing punctuation, and typically concise. Error::description() should not be implemented. It has been deprecated and users should always use Display instead of description() to print the error. Examples from the standard library ParseBoolError is returned when failing to parse a bool from a string. Examples of error messages "unexpected end of file" "provided string was not `true` or `false`" "invalid IP address syntax" "second time provided was later than self" "invalid UTF-8 sequence of {} bytes from index {}" "environment variable was not valid unicode: {:?}" Binary number types provide Hex , Octal , Binary formatting (C-NUM-FMT) std::fmt::UpperHex std::fmt::LowerHex std::fmt::Octal std::fmt::Binary These traits control the representation of a type under the {:X} , {:x} , {:o} , and {:b} format specifiers. Implement these traits for any number type on which you would consider doing bitwise manipulations like | or & . This is especially appropriate for bitflag types. Numeric quantity types like struct Nanoseconds(u64) probably do not need these. Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE) The standard library contains these two impls: #![allow(unused)] fn main() { impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ } impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ } } That means any function that accepts R: Read or W: Write generic parameters by value can be called with a mut reference if necessary. In the documentation of such functions, briefly remind users that a mut reference can be passed. New Rust users often struggle with this. They may have opened a file and want to read multiple pieces of data out of it, but the function to read one piece consumes the reader by value, so they are stuck. The solution would be to leverage one of the above impls and pass &mut f instead of f as the reader parameter. Examples flate2::read::GzDecoder::new flate2::write::GzEncoder::new serde_json::from_reader serde_json::to_writer | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---exclude | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#compilation-options | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#examples | Interoperability - Rust API Guidelines About Checklist 1. Naming 2. Interoperability 3. Macros 4. Documentation 5. Predictability 6. Flexibility 7. Type safety 8. Dependability 9. Debuggability 10. Future proofing 11. Necessities External links Light (default) Rust Coal Navy Ayu Rust API Guidelines Interoperability Types eagerly implement common traits (C-COMMON-TRAITS) Rust's trait system does not allow orphans : roughly, every impl must live either in the crate that defines the trait or the implementing type. Consequently, crates that define new types should eagerly implement all applicable, common traits. To see why, consider the following situation: Crate std defines trait Display . Crate url defines type Url , without implementing Display . Crate webapp imports from both std and url , There is no way for webapp to add Display to Url , since it defines neither. (Note: the newtype pattern can provide an efficient, but inconvenient workaround.) The most important common traits to implement from std are: Copy Clone Eq PartialEq Ord PartialOrd Hash Debug Display Default Note that it is common and expected for types to implement both Default and an empty new constructor. new is the constructor convention in Rust, and users expect it to exist, so if it is reasonable for the basic constructor to take no arguments, then it should, even if it is functionally identical to default . Conversions use the standard traits From , AsRef , AsMut (C-CONV-TRAITS) The following conversion traits should be implemented where it makes sense: From TryFrom AsRef AsMut The following conversion traits should never be implemented: Into TryInto These traits have a blanket impl based on From and TryFrom . Implement those instead. Examples from the standard library From<u16> is implemented for u32 because a smaller integer can always be converted to a bigger integer. From<u32> is not implemented for u16 because the conversion may not be possible if the integer is too big. TryFrom<u32> is implemented for u16 and returns an error if the integer is too big to fit in u16 . From<Ipv6Addr> is implemented for IpAddr , which is a type that can represent both v4 and v6 IP addresses. Collections implement FromIterator and Extend (C-COLLECT) FromIterator and Extend enable collections to be used conveniently with the following iterator methods: Iterator::collect Iterator::partition Iterator::unzip FromIterator is for creating a new collection containing items from an iterator, and Extend is for adding items from an iterator onto an existing collection. Examples from the standard library Vec<T> implements both FromIterator<T> and Extend<T> . Data structures implement Serde's Serialize , Deserialize (C-SERDE) Types that play the role of a data structure should implement Serialize and Deserialize . There is a continuum of types between things that are clearly a data structure and things that are clearly not, with gray area in between. LinkedHashMap and IpAddr are data structures. It would be completely reasonable for somebody to want to read in a LinkedHashMap or IpAddr from a JSON file, or send one over IPC to another process. LittleEndian is not a data structure. It is a marker used by the byteorder crate to optimize at compile time for bytes in a particular order, and in fact an instance of LittleEndian can never exist at runtime. So these are clear-cut examples; the #rust or #serde IRC channels can help assess more ambiguous cases if necessary. If a crate does not already depend on Serde for other reasons, it may wish to gate Serde impls behind a Cargo cfg. This way downstream libraries only need to pay the cost of compiling Serde if they need those impls to exist. For consistency with other Serde-based libraries, the name of the Cargo cfg should be simply "serde" . Do not use a different name for the cfg like "serde_impls" or "serde_serialization" . The canonical implementation looks like this when not using derive: [dependencies] serde = { version = "1.0", optional = true } #![allow(unused)] fn main() { pub struct T { /* ... */ } #[cfg(feature = "serde")] impl Serialize for T { /* ... */ } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for T { /* ... */ } } And when using derive: [dependencies] serde = { version = "1.0", optional = true, features = ["derive"] } #![allow(unused)] fn main() { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct T { /* ... */ } } Types are Send and Sync where possible (C-SEND-SYNC) Send and Sync are automatically implemented when the compiler determines it is appropriate. In types that manipulate raw pointers, be vigilant that the Send and Sync status of your type accurately reflects its thread safety characteristics. Tests like the following can help catch unintentional regressions in whether the type implements Send or Sync . #![allow(unused)] fn main() { #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<MyStrangeType>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<MyStrangeType>(); } } Error types are meaningful and well-behaved (C-GOOD-ERR) An error type is any type E used in a Result<T, E> returned by any public function of your crate. Error types should always implement the std::error::Error trait which is the mechanism by which error handling libraries like error-chain abstract over different types of errors, and which allows the error to be used as the source() of another error. Additionally, error types should implement the Send and Sync traits. An error that is not Send cannot be returned by a thread run with thread::spawn . An error that is not Sync cannot be passed across threads using an Arc . These are common requirements for basic error handling in a multithreaded application. Send and Sync are also important for being able to package a custom error into an IO error using std::io::Error::new , which requires a trait bound of Error + Send + Sync . One place to be vigilant about this guideline is in functions that return Error trait objects, for example reqwest::Error::get_ref . Typically Error + Send + Sync + 'static will be the most useful for callers. The addition of 'static allows the trait object to be used with Error::downcast_ref . Never use () as an error type, even where there is no useful additional information for the error to carry. () does not implement Error so it cannot be used with error handling libraries like error-chain . () does not implement Display so a user would need to write an error message of their own if they want to fail because of the error. () has an unhelpful Debug representation for users that decide to unwrap() the error. It would not be semantically meaningful for a downstream library to implement From<()> for their error type, so () as an error type cannot be used with the ? operator. Instead, define a meaningful error type specific to your crate or to the individual function. Provide appropriate Error and Display impls. If there is no useful information for the error to carry, it can be implemented as a unit struct. #![allow(unused)] fn main() { use std::error::Error; use std::fmt::Display; // Instead of this... fn do_the_thing() -> Result<Wow, ()> // Prefer this... fn do_the_thing() -> Result<Wow, DoError> #[derive(Debug)] struct DoError; impl Display for DoError { /* ... */ } impl Error for DoError { /* ... */ } } The error message given by the Display representation of an error type should be lowercase without trailing punctuation, and typically concise. Error::description() should not be implemented. It has been deprecated and users should always use Display instead of description() to print the error. Examples from the standard library ParseBoolError is returned when failing to parse a bool from a string. Examples of error messages "unexpected end of file" "provided string was not `true` or `false`" "invalid IP address syntax" "second time provided was later than self" "invalid UTF-8 sequence of {} bytes from index {}" "environment variable was not valid unicode: {:?}" Binary number types provide Hex , Octal , Binary formatting (C-NUM-FMT) std::fmt::UpperHex std::fmt::LowerHex std::fmt::Octal std::fmt::Binary These traits control the representation of a type under the {:X} , {:x} , {:o} , and {:b} format specifiers. Implement these traits for any number type on which you would consider doing bitwise manipulations like | or & . This is especially appropriate for bitflag types. Numeric quantity types like struct Nanoseconds(u64) probably do not need these. Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE) The standard library contains these two impls: #![allow(unused)] fn main() { impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ } impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ } } That means any function that accepts R: Read or W: Write generic parameters by value can be called with a mut reference if necessary. In the documentation of such functions, briefly remind users that a mut reference can be passed. New Rust users often struggle with this. They may have opened a file and want to read multiple pieces of data out of it, but the function to read one piece consumes the reader by value, so they are stuck. The solution would be to leverage one of the above impls and pass &mut f instead of f as the reader parameter. Examples flate2::read::GzDecoder::new flate2::write::GzEncoder::new serde_json::from_reader serde_json::to_writer | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package--v | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package--F | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://vi-vn.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1v_OJQfV5Zcu-cblOHFXfPicMkZBPGWKUMR8y2VtHCkhFimX0DXmuO_lS7lSOvuxvJGvNENLC3hXctnK0aEhIreuGRGjRkAY5nzNTCCWlumoLGOzuQm7GYuIQhI_WWXvHN-cB9_Akw-iZt | Facebook Facebook Email hoặc điện thoại Mật khẩu Bạn quên tài khoản ư? Tạo tài khoản mới Bạn tạm thời bị chặn Bạn tạm thời bị chặn Có vẻ như bạn đang dùng nhầm tính năng này do sử dụng quá nhanh. Bạn tạm thời đã bị chặn sử dụng nó. Back Tiếng Việt 한국어 English (US) Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch Đăng ký Đăng nhập Messenger Facebook Lite Video Meta Pay Cửa hàng trên Meta Meta Quest Ray-Ban Meta Meta AI Nội dung khác do Meta AI tạo Instagram Threads Trung tâm thông tin bỏ phiếu Chính sách quyền riêng tư Trung tâm quyền riêng tư Giới thiệu Tạo quảng cáo Tạo Trang Nhà phát triển Tuyển dụng Cookie Lựa chọn quảng cáo Điều khoản Trợ giúp Tải thông tin liên hệ lên & đối tượng không phải người dùng Cài đặt Nhật ký hoạt động Meta © 2026 | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/items/generics.html | Generic parameters - The Rust Reference Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Rust Reference [items .generics] Generic parameters [items .generics .syntax] Syntax GenericParams → < ( GenericParam ( , GenericParam ) * , ? ) ? > GenericParam → OuterAttribute * ( LifetimeParam | TypeParam | ConstParam ) LifetimeParam → Lifetime ( : LifetimeBounds ) ? TypeParam → IDENTIFIER ( : TypeParamBounds ? ) ? ( = Type ) ? ConstParam → const IDENTIFIER : Type ( = ( BlockExpression | IDENTIFIER | - ? LiteralExpression ) ) ? Show Railroad GenericParams < GenericParam , GenericParam , > GenericParam OuterAttribute LifetimeParam TypeParam ConstParam LifetimeParam Lifetime : LifetimeBounds TypeParam IDENTIFIER : TypeParamBounds = Type ConstParam const IDENTIFIER : Type = BlockExpression IDENTIFIER - LiteralExpression [items .generics .syntax .intro] Functions , type aliases , structs , enumerations , unions , traits , and implementations may be parameterized by types, constants, and lifetimes. These parameters are listed in angle brackets ( <...> ) , usually immediately after the name of the item and before its definition. For implementations, which don’t have a name, they come directly after impl . [items .generics .syntax .decl-order] The order of generic parameters is restricted to lifetime parameters and then type and const parameters intermixed. [items .generics .syntax .duplicate-params] The same parameter name may not be declared more than once in a GenericParams list. Some examples of items with type, const, and lifetime parameters: #![allow(unused)] fn main() { fn foo<'a, T>() {} trait A<U> {} struct Ref<'a, T> where T: 'a { r: &'a T } struct InnerArray<T, const N: usize>([T; N]); struct EitherOrderWorks<const N: bool, U>(U); } [items .generics .syntax .scope] Generic parameters are in scope within the item definition where they are declared. They are not in scope for items declared within the body of a function as described in item declarations . See generic parameter scopes for more details. [items .generics .builtin-generic-types] References , raw pointers , arrays , slices , tuples , and function pointers have lifetime or type parameters as well, but are not referred to with path syntax. [items .generics .invalid-lifetimes] '_ and 'static are not valid lifetime parameter names. [items .generics .const] Const generics [items .generics .const .intro] Const generic parameters allow items to be generic over constant values. [items .generics .const .namespace] The const identifier introduces a name in the value namespace for the constant parameter, and all instances of the item must be instantiated with a value of the given type. [items .generics .const .allowed-types] The only allowed types of const parameters are u8 , u16 , u32 , u64 , u128 , usize , i8 , i16 , i32 , i64 , i128 , isize , char and bool . [items .generics .const .usage] Const parameters can be used anywhere a const item can be used, with the exception that when used in a type or array repeat expression , it must be standalone (as described below). That is, they are allowed in the following places: As an applied const to any type which forms a part of the signature of the item in question. As part of a const expression used to define an associated const , or as a parameter to an associated type . As a value in any runtime expression in the body of any functions in the item. As a parameter to any type used in the body of any functions in the item. As a part of the type of any fields in the item. #![allow(unused)] fn main() { // Examples where const generic parameters can be used. // Used in the signature of the item itself. fn foo<const N: usize>(arr: [i32; N]) { // Used as a type within a function body. let x: [i32; N]; // Used as an expression. println!("{}", N * 2); } // Used as a field of a struct. struct Foo<const N: usize>([i32; N]); impl<const N: usize> Foo<N> { // Used as an associated constant. const CONST: usize = N * 4; } trait Trait { type Output; } impl<const N: usize> Trait for Foo<N> { // Used as an associated type. type Output = [i32; N]; } } #![allow(unused)] fn main() { // Examples where const generic parameters cannot be used. fn foo<const N: usize>() { // Cannot use in item definitions within a function body. const BAD_CONST: [usize; N] = [1; N]; static BAD_STATIC: [usize; N] = [1; N]; fn inner(bad_arg: [usize; N]) { let bad_value = N * 2; } type BadAlias = [usize; N]; struct BadStruct([usize; N]); } } [items .generics .const .standalone] As a further restriction, const parameters may only appear as a standalone argument inside of a type or array repeat expression . In those contexts, they may only be used as a single segment path expression , possibly inside a block (such as N or {N} ). That is, they cannot be combined with other expressions. #![allow(unused)] fn main() { // Examples where const parameters may not be used. // Not allowed to combine in other expressions in types, such as the // arithmetic expression in the return type here. fn bad_function<const N: usize>() -> [u8; {N + 1}] { // Similarly not allowed for array repeat expressions. [1; {N + 1}] } } [items .generics .const .argument] A const argument in a path specifies the const value to use for that item. [items .generics .const .argument .const-expr] The argument must either be an inferred const or be a const expression of the type ascribed to the const parameter. The const expression must be a block expression (surrounded with braces) unless it is a single path segment (an IDENTIFIER ) or a literal (with a possibly leading - token). Note This syntactic restriction is necessary to avoid requiring infinite lookahead when parsing an expression inside of a type. #![allow(unused)] fn main() { struct S<const N: i64>; const C: i64 = 1; fn f<const N: i64>() -> S<N> { S } let _ = f::<1>(); // Literal. let _ = f::<-1>(); // Negative literal. let _ = f::<{ 1 + 2 }>(); // Constant expression. let _ = f::<C>(); // Single segment path. let _ = f::<{ C + 1 }>(); // Constant expression. let _: S<1> = f::<_>(); // Inferred const. let _: S<1> = f::<(((_)))>(); // Inferred const. } Note In a generic argument list, an inferred const is parsed as an inferred type but then semantically treated as a separate kind of const generic argument . [items .generics .const .inferred] Tests Tests with this rule: tests/ui/const-generics/generic_arg_infer/paren_infer.rs Where a const argument is expected, an _ (optionally surrounded by any number of matching parentheses), called the inferred const ( path rules , array expression rules ), can be used instead. This asks the compiler to infer the const argument if possible based on surrounding information. #![allow(unused)] fn main() { fn make_buf<const N: usize>() -> [u8; N] { [0; _] // ^ Infers `N`. } let _: [u8; 1024] = make_buf::<_>(); // ^ Infers `1024`. } Note An inferred const is not semantically an expression and so is not accepted within braces. #![allow(unused)] fn main() { fn f<const N: usize>() -> [u8; N] { [0; _] } let _: [_; 1] = f::<{ _ }>(); // ^ ERROR `_` not allowed here } [items .generics .const .inferred .constraint] The inferred const cannot be used in item signatures. #![allow(unused)] fn main() { fn f<const N: usize>(x: [u8; N]) -> [u8; _] { x } // ^ ERROR not allowed } [items .generics .const .type-ambiguity] When there is ambiguity if a generic argument could be resolved as either a type or const argument, it is always resolved as a type. Placing the argument in a block expression can force it to be interpreted as a const argument. #![allow(unused)] fn main() { type N = u32; struct Foo<const N: usize>; // The following is an error, because `N` is interpreted as the type alias `N`. fn foo<const N: usize>() -> Foo<N> { todo!() } // ERROR // Can be fixed by wrapping in braces to force it to be interpreted as the `N` // const parameter: fn bar<const N: usize>() -> Foo<{ N }> { todo!() } // ok } [items .generics .const .variance] Unlike type and lifetime parameters, const parameters can be declared without being used inside of a parameterized item, with the exception of implementations as described in generic implementations : #![allow(unused)] fn main() { // ok struct Foo<const N: usize>; enum Bar<const M: usize> { A, B } // ERROR: unused parameter struct Baz<T>; struct Biz<'a>; struct Unconstrained; impl<const N: usize> Unconstrained {} } [items .generics .const .exhaustiveness] When resolving a trait bound obligation, the exhaustiveness of all implementations of const parameters is not considered when determining if the bound is satisfied. For example, in the following, even though all possible const values for the bool type are implemented, it is still an error that the trait bound is not satisfied: #![allow(unused)] fn main() { struct Foo<const B: bool>; trait Bar {} impl Bar for Foo<true> {} impl Bar for Foo<false> {} fn needs_bar(_: impl Bar) {} fn generic<const B: bool>() { let v = Foo::<B>; needs_bar(v); // ERROR: trait bound `Foo<B>: Bar` is not satisfied } } [items .generics .where] Where clauses [items .generics .where .syntax] Syntax WhereClause → where ( WhereClauseItem , ) * WhereClauseItem ? WhereClauseItem → LifetimeWhereClauseItem | TypeBoundWhereClauseItem LifetimeWhereClauseItem → Lifetime : LifetimeBounds TypeBoundWhereClauseItem → ForLifetimes ? Type : TypeParamBounds ? Show Railroad WhereClause where WhereClauseItem , WhereClauseItem WhereClauseItem LifetimeWhereClauseItem TypeBoundWhereClauseItem LifetimeWhereClauseItem Lifetime : LifetimeBounds TypeBoundWhereClauseItem ForLifetimes Type : TypeParamBounds [items .generics .where .intro] Where clauses provide another way to specify bounds on type and lifetime parameters as well as a way to specify bounds on types that aren’t type parameters. [items .generics .where .higher-ranked-lifetimes] The for keyword can be used to introduce higher-ranked lifetimes . It only allows LifetimeParam parameters. #![allow(unused)] fn main() { struct A<T> where T: Iterator, // Could use A<T: Iterator> instead T::Item: Copy, // Bound on an associated type String: PartialEq<T>, // Bound on `String`, using the type parameter i32: Default, // Allowed, but not useful { f: T, } } [items .generics .attributes] Attributes Generic lifetime and type parameters allow attributes on them. There are no built-in attributes that do anything in this position, although custom derive attributes may give meaning to it. This example shows using a custom derive attribute to modify the meaning of a generic parameter. // Assume that the derive for MyFlexibleClone declared `my_flexible_clone` as // an attribute it understands. #[derive(MyFlexibleClone)] struct Foo<#[my_flexible_clone(unbounded)] H> { a: *const H } | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---target-dir | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#feature-selection | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---no-default-features | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---features | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#package-selection | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---manifest-path | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---target | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---all-features | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---allow-dirty | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---offline | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/reference/config.html#buildtarget | Configuration - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book Configuration This document explains how Cargo’s configuration system works, as well as available keys or configuration. For configuration of a package through its manifest, see the manifest format . Hierarchical structure Cargo allows local configuration for a particular package as well as global configuration. It looks for configuration files in the current directory and all parent directories. If, for example, Cargo were invoked in /projects/foo/bar/baz , then the following configuration files would be probed for and unified in this order: /projects/foo/bar/baz/.cargo/config.toml /projects/foo/bar/.cargo/config.toml /projects/foo/.cargo/config.toml /projects/.cargo/config.toml /.cargo/config.toml $CARGO_HOME/config.toml which defaults to: Windows: %USERPROFILE%\.cargo\config.toml Unix: $HOME/.cargo/config.toml With this structure, you can specify configuration per-package, and even possibly check it into version control. You can also specify personal defaults with a configuration file in your home directory. If a key is specified in multiple config files, the values will get merged together. Numbers, strings, and booleans will use the value in the deeper config directory taking precedence over ancestor directories, where the home directory is the lowest priority. Arrays will be joined together with higher precedence items being placed later in the merged array. At present, when being invoked from a workspace, Cargo does not read config files from crates within the workspace. i.e. if a workspace has two crates in it, named /projects/foo/bar/baz/mylib and /projects/foo/bar/baz/mybin , and there are Cargo configs at /projects/foo/bar/baz/mylib/.cargo/config.toml and /projects/foo/bar/baz/mybin/.cargo/config.toml , Cargo does not read those configuration files if it is invoked from the workspace root ( /projects/foo/bar/baz/ ). Note: Cargo also reads config files without the .toml extension, such as .cargo/config . Support for the .toml extension was added in version 1.39 and is the preferred form. If both files exist, Cargo will use the file without the extension. Configuration format Configuration files are written in the TOML format (like the manifest), with simple key-value pairs inside of sections (tables). The following is a quick overview of all settings, with detailed descriptions found below. paths = ["/path/to/override"] # path dependency overrides [alias] # command aliases b = "build" c = "check" t = "test" r = "run" rr = "run --release" recursive_example = "rr --example recursions" space_example = ["run", "--release", "--", "\"command list\""] [build] jobs = 1 # number of parallel jobs, defaults to # of CPUs rustc = "rustc" # the rust compiler tool rustc-wrapper = "…" # run this wrapper instead of `rustc` rustc-workspace-wrapper = "…" # run this wrapper instead of `rustc` for workspace members rustdoc = "rustdoc" # the doc generator tool target = "triple" # build for the target triple (ignored by `cargo install`) target-dir = "target" # path of where to place generated artifacts build-dir = "target" # path of where to place intermediate build artifacts rustflags = ["…", "…"] # custom flags to pass to all compiler invocations rustdocflags = ["…", "…"] # custom flags to pass to rustdoc incremental = true # whether or not to enable incremental compilation dep-info-basedir = "…" # path for the base directory for targets in depfiles [credential-alias] # Provides a way to define aliases for credential providers. my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] [doc] browser = "chromium" # browser to use with `cargo doc --open`, # overrides the `BROWSER` environment variable [env] # Set ENV_VAR_NAME=value for any process run by Cargo ENV_VAR_NAME = "value" # Set even if already present in environment ENV_VAR_NAME_2 = { value = "value", force = true } # `value` is relative to the parent of `.cargo/config.toml`, env var will be the full absolute path ENV_VAR_NAME_3 = { value = "relative/path", relative = true } [future-incompat-report] frequency = 'always' # when to display a notification about a future incompat report [cache] auto-clean-frequency = "1 day" # How often to perform automatic cache cleaning [cargo-new] vcs = "none" # VCS to use ('git', 'hg', 'pijul', 'fossil', 'none') [http] debug = false # HTTP debugging proxy = "host:port" # HTTP proxy in libcurl format ssl-version = "tlsv1.3" # TLS version to use ssl-version.max = "tlsv1.3" # maximum TLS version ssl-version.min = "tlsv1.1" # minimum TLS version timeout = 30 # timeout for each HTTP request, in seconds low-speed-limit = 10 # network timeout threshold (bytes/sec) cainfo = "cert.pem" # path to Certificate Authority (CA) bundle proxy-cainfo = "cert.pem" # path to proxy Certificate Authority (CA) bundle check-revoke = true # check for SSL certificate revocation multiplexing = true # HTTP/2 multiplexing user-agent = "…" # the user-agent header [install] root = "/some/path" # `cargo install` destination directory [net] retry = 3 # network retries git-fetch-with-cli = true # use the `git` executable for git operations offline = true # do not access the network [net.ssh] known-hosts = ["..."] # known SSH host keys [patch.<registry>] # Same keys as for [patch] in Cargo.toml [profile.<name>] # Modify profile settings via config. inherits = "dev" # Inherits settings from [profile.dev]. opt-level = 0 # Optimization level. debug = true # Include debug info. split-debuginfo = '...' # Debug info splitting behavior. strip = "none" # Removes symbols or debuginfo. debug-assertions = true # Enables debug assertions. overflow-checks = true # Enables runtime integer overflow checks. lto = false # Sets link-time optimization. panic = 'unwind' # The panic strategy. incremental = true # Incremental compilation. codegen-units = 16 # Number of code generation units. rpath = false # Sets the rpath linking option. [profile.<name>.build-override] # Overrides build-script settings. # Same keys for a normal profile. [profile.<name>.package.<name>] # Override profile for a package. # Same keys for a normal profile (minus `panic`, `lto`, and `rpath`). [resolver] incompatible-rust-versions = "allow" # Specifies how resolver reacts to these [registries.<name>] # registries other than crates.io index = "…" # URL of the registry index token = "…" # authentication token for the registry credential-provider = "cargo:token" # The credential provider for this registry. [registries.crates-io] protocol = "sparse" # The protocol to use to access crates.io. [registry] default = "…" # name of the default registry token = "…" # authentication token for crates.io credential-provider = "cargo:token" # The credential provider for crates.io. global-credential-providers = ["cargo:token"] # The credential providers to use by default. [source.<name>] # source definition and replacement replace-with = "…" # replace this source with the given named source directory = "…" # path to a directory source registry = "…" # URL to a registry source local-registry = "…" # path to a local registry source git = "…" # URL of a git repository source branch = "…" # branch name for the git repository tag = "…" # tag name for the git repository rev = "…" # revision for the git repository [target.<triple>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` rustdocflags = ["…", "…"] # custom flags for `rustdoc` [target.<cfg>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` [target.<triple>.<links>] # `links` build script override rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] quiet = false # whether cargo output is quiet verbose = false # whether cargo provides verbose output color = 'auto' # whether cargo colorizes output hyperlinks = true # whether cargo inserts links into output unicode = true # whether cargo can render output using non-ASCII unicode characters progress.when = 'auto' # whether cargo shows progress bar progress.width = 80 # width of progress bar progress.term-integration = true # whether cargo reports progress to terminal emulator Environment variables Cargo can also be configured through environment variables in addition to the TOML configuration files. For each configuration key of the form foo.bar the environment variable CARGO_FOO_BAR can also be used to define the value. Keys are converted to uppercase, dots and dashes are converted to underscores. For example the target.x86_64-unknown-linux-gnu.runner key can also be defined by the CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER environment variable. Environment variables will take precedence over TOML configuration files. Currently only integer, boolean, string and some array values are supported to be defined by environment variables. Descriptions below indicate which keys support environment variables and otherwise they are not supported due to technical issues . In addition to the system above, Cargo recognizes a few other specific environment variables . Command-line overrides Cargo also accepts arbitrary configuration overrides through the --config command-line option. The argument should be in TOML syntax of KEY=VALUE or provided as a path to an extra configuration file: # With `KEY=VALUE` in TOML syntax cargo --config net.git-fetch-with-cli=true fetch # With a path to a configuration file cargo --config ./path/to/my/extra-config.toml fetch The --config option may be specified multiple times, in which case the values are merged in left-to-right order, using the same merging logic that is used when multiple configuration files apply. Configuration values specified this way take precedence over environment variables, which take precedence over configuration files. When the --config option is provided as an extra configuration file, The configuration file loaded this way follow the same precedence rules as other options specified directly with --config . Some examples of what it looks like using Bourne shell syntax: # Most shells will require escaping. cargo --config http.proxy=\"http://example.com\" … # Spaces may be used. cargo --config "net.git-fetch-with-cli = true" … # TOML array example. Single quotes make it easier to read and write. cargo --config 'build.rustdocflags = ["--html-in-header", "header.html"]' … # Example of a complex TOML key. cargo --config "target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))'.runner = 'my-runner'" … # Example of overriding a profile setting. cargo --config profile.dev.package.image.opt-level=3 … Config-relative paths Paths in config files may be absolute, relative, or a bare name without any path separators. Paths for executables without a path separator will use the PATH environment variable to search for the executable. Paths for non-executables will be relative to where the config value is defined. In particular, rules are: For environment variables, paths are relative to the current working directory. For config values loaded directly from the --config KEY=VALUE option, paths are relative to the current working directory. For config files, paths are relative to the parent directory of the directory where the config files were defined, no matter those files are from either the hierarchical probing or the --config <path> option. Note: To maintain consistency with existing .cargo/config.toml probing behavior, it is by design that a path in a config file passed via --config <path> is also relative to two levels up from the config file itself. To avoid unexpected results, the rule of thumb is putting your extra config files at the same level of discovered .cargo/config.toml in your project. For instance, given a project /my/project , it is recommended to put config files under /my/project/.cargo or a new directory at the same level, such as /my/project/.config . # Relative path examples. [target.x86_64-unknown-linux-gnu] runner = "foo" # Searches `PATH` for `foo`. [source.vendored-sources] # Directory is relative to the parent where `.cargo/config.toml` is located. # For example, `/my/project/.cargo/config.toml` would result in `/my/project/vendor`. directory = "vendor" Executable paths with arguments Some Cargo commands invoke external programs, which can be configured as a path and some number of arguments. The value may be an array of strings like ['/path/to/program', 'somearg'] or a space-separated string like '/path/to/program somearg' . If the path to the executable contains a space, the list form must be used. If Cargo is passing other arguments to the program such as a path to open or run, they will be passed after the last specified argument in the value of an option of this format. If the specified program does not have path separators, Cargo will search PATH for its executable. Credentials Configuration values with sensitive information are stored in the $CARGO_HOME/credentials.toml file. This file is automatically created and updated by cargo login and cargo logout when using the cargo:token credential provider. Tokens are used by some Cargo commands such as cargo publish for authenticating with remote registries. Care should be taken to protect the tokens and to keep them secret. It follows the same format as Cargo config files. [registry] token = "…" # Access token for crates.io [registries.<name>] token = "…" # Access token for the named registry As with most other config values, tokens may be specified with environment variables. The token for crates.io may be specified with the CARGO_REGISTRY_TOKEN environment variable. Tokens for other registries may be specified with environment variables of the form CARGO_REGISTRIES_<name>_TOKEN where <name> is the name of the registry in all capital letters. Note: Cargo also reads and writes credential files without the .toml extension, such as .cargo/credentials . Support for the .toml extension was added in version 1.39. In version 1.68, Cargo writes to the file with the extension by default. However, for backward compatibility reason, when both files exist, Cargo will read and write the file without the extension. Configuration keys This section documents all configuration keys. The description for keys with variable parts are annotated with angled brackets like target.<triple> where the <triple> part can be any target triple like target.x86_64-pc-windows-msvc . paths Type: array of strings (paths) Default: none Environment: not supported An array of paths to local packages which are to be used as overrides for dependencies. For more information see the Overriding Dependencies guide . [alias] Type: string or array of strings Default: see below Environment: CARGO_ALIAS_<name> The [alias] table defines CLI command aliases. For example, running cargo b is an alias for running cargo build . Each key in the table is the subcommand, and the value is the actual command to run. The value may be an array of strings, where the first element is the command and the following are arguments. It may also be a string, which will be split on spaces into subcommand and arguments. The following aliases are built-in to Cargo: [alias] b = "build" c = "check" d = "doc" t = "test" r = "run" rm = "remove" Aliases are not allowed to redefine existing built-in commands. Aliases are recursive: [alias] rr = "run --release" recursive_example = "rr --example recursions" [build] The [build] table controls build-time operations and compiler settings. build.jobs Type: integer or string Default: number of logical CPUs Environment: CARGO_BUILD_JOBS Sets the maximum number of compiler processes to run in parallel. If negative, it sets the maximum number of compiler processes to the number of logical CPUs plus provided value. Should not be 0. If a string default is provided, it sets the value back to defaults. Can be overridden with the --jobs CLI option. build.rustc Type: string (program path) Default: "rustc" Environment: CARGO_BUILD_RUSTC or RUSTC Sets the executable to use for rustc . build.rustc-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WRAPPER or RUSTC_WRAPPER Sets a wrapper to execute instead of rustc . The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). build.rustc-workspace-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER or RUSTC_WORKSPACE_WRAPPER Sets a wrapper to execute instead of rustc , for workspace members only. When building a single-package project without workspaces, that package is considered to be the workspace. The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). It affects the filename hash so that artifacts produced by the wrapper are cached separately. If both rustc-wrapper and rustc-workspace-wrapper are set, then they will be nested: the final invocation is $RUSTC_WRAPPER $RUSTC_WORKSPACE_WRAPPER $RUSTC . build.rustdoc Type: string (program path) Default: "rustdoc" Environment: CARGO_BUILD_RUSTDOC or RUSTDOC Sets the executable to use for rustdoc . build.target Type: string or array of strings Default: host platform Environment: CARGO_BUILD_TARGET The default target platform triples to compile to. Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. Can be overridden with the --target CLI option. [build] target = ["x86_64-unknown-linux-gnu", "i686-unknown-linux-gnu"] build.target-dir Type: string (path) Default: "target" Environment: CARGO_BUILD_TARGET_DIR or CARGO_TARGET_DIR The path to where all compiler output is placed. The default if not specified is a directory named target located at the root of the workspace. Can be overridden with the --target-dir CLI option. For more information see the build cache documentation . build.build-dir Type: string (path) Default: Defaults to the value of build.target-dir Environment: CARGO_BUILD_BUILD_DIR The directory where intermediate build artifacts will be stored. Intermediate artifacts are produced by Rustc/Cargo during the build process. This option supports path templating. Available template variables: {workspace-root} resolves to root of the current workspace. {cargo-cache-home} resolves to CARGO_HOME {workspace-path-hash} resolves to a hash of the manifest path For more information see the build cache documentation . build.rustflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS or RUSTFLAGS Extra command-line flags to pass to rustc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTFLAGS environment variable. RUSTFLAGS environment variable. All matching target.<triple>.rustflags and target.<cfg>.rustflags config entries joined together. build.rustflags config value. Additional flags may also be passed with the cargo rustc command. If the --target flag (or build.target ) is used, then the flags will only be passed to the compiler for the target. Things being built for the host, such as build scripts or proc macros, will not receive the args. Without --target , the flags will be passed to all compiler invocations (including build scripts and proc macros) because dependencies are shared. If you have args that you do not want to pass to build scripts or proc macros and are building for the host, pass --target with the host triple . It is not recommended to pass in flags that Cargo itself usually manages. For example, the flags driven by profiles are best handled by setting the appropriate profile setting. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.rustdocflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTDOCFLAGS or CARGO_ENCODED_RUSTDOCFLAGS or RUSTDOCFLAGS Extra command-line flags to pass to rustdoc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTDOCFLAGS environment variable. RUSTDOCFLAGS environment variable. All matching target.<triple>.rustdocflags config entries joined together. build.rustdocflags config value. Additional flags may also be passed with the cargo rustdoc command. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.incremental Type: bool Default: from profile Environment: CARGO_BUILD_INCREMENTAL or CARGO_INCREMENTAL Whether or not to perform incremental compilation . The default if not set is to use the value from the profile . Otherwise this overrides the setting of all profiles. The CARGO_INCREMENTAL environment variable can be set to 1 to force enable incremental compilation for all profiles, or 0 to disable it. This env var overrides the config setting. build.dep-info-basedir Type: string (path) Default: none Environment: CARGO_BUILD_DEP_INFO_BASEDIR Strips the given path prefix from dep info file paths. This config setting is intended to convert absolute paths to relative paths for tools that require relative paths. The setting itself is a config-relative path. So, for example, a value of "." would strip all paths starting with the parent directory of the .cargo directory. build.pipelining This option is deprecated and unused. Cargo always has pipelining enabled. [credential-alias] Type: string or array of strings Default: empty Environment: CARGO_CREDENTIAL_ALIAS_<name> The [credential-alias] table defines credential provider aliases. These aliases can be referenced as an element of the registry.global-credential-providers array, or as a credential provider for a specific registry under registries.<NAME>.credential-provider . If specified as a string, the value will be split on spaces into path and arguments. For example, to define an alias called my-alias : [credential-alias] my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] See Registry Authentication for more information. [doc] The [doc] table defines options for the cargo doc command. doc.browser Type: string or array of strings ( program path with args ) Default: BROWSER environment variable, or, if that is missing, opening the link in a system specific way This option sets the browser to be used by cargo doc , overriding the BROWSER environment variable when opening documentation with the --open option. [cargo-new] The [cargo-new] table defines defaults for the cargo new command. cargo-new.name This option is deprecated and unused. cargo-new.email This option is deprecated and unused. cargo-new.vcs Type: string Default: "git" or "none" Environment: CARGO_CARGO_NEW_VCS Specifies the source control system to use for initializing a new repository. Valid values are git , hg (for Mercurial), pijul , fossil or none to disable this behavior. Defaults to git , or none if already inside a VCS repository. Can be overridden with the --vcs CLI option. [env] The [env] section allows you to set additional environment variables for build scripts, rustc invocations, cargo run and cargo build . [env] OPENSSL_DIR = "/opt/openssl" By default, the variables specified will not override values that already exist in the environment. This behavior can be changed by setting the force flag. Setting the relative flag evaluates the value as a config-relative path that is relative to the parent directory of the .cargo directory that contains the config.toml file. The value of the environment variable will be the full absolute path. [env] TMPDIR = { value = "/home/tmp", force = true } OPENSSL_DIR = { value = "vendor/openssl", relative = true } [future-incompat-report] The [future-incompat-report] table controls setting for future incompat reporting future-incompat-report.frequency Type: string Default: "always" Environment: CARGO_FUTURE_INCOMPAT_REPORT_FREQUENCY Controls how often we display a notification to the terminal when a future incompat report is available. Possible values: always (default): Always display a notification when a command (e.g. cargo build ) produces a future incompat report never : Never display a notification [cache] The [cache] table defines settings for cargo’s caches. Global caches When running cargo commands, Cargo will automatically track which files you are using within the global cache. Periodically, Cargo will delete files that have not been used for some period of time. It will delete files that have to be downloaded from the network if they have not been used in 3 months. Files that can be generated without network access will be deleted if they have not been used in 1 month. The automatic deletion of files only occurs when running commands that are already doing a significant amount of work, such as all of the build commands ( cargo build , cargo test , cargo check , etc.), and cargo fetch . Automatic deletion is disabled if cargo is offline such as with --offline or --frozen to avoid deleting artifacts that may need to be used if you are offline for a long period of time. Note : This tracking is currently only implemented for the global cache in Cargo’s home directory. This includes registry indexes and source files downloaded from registries and git dependencies. Support for tracking build artifacts is not yet implemented, and tracked in cargo#13136 . Additionally, there is an unstable feature to support manually triggering cache cleaning, and to further customize the configuration options. See the Unstable chapter for more information. cache.auto-clean-frequency Type: string Default: "1 day" Environment: CARGO_CACHE_AUTO_CLEAN_FREQUENCY This option defines how often Cargo will automatically delete unused files in the global cache. This does not define how old the files must be, those thresholds are described above . It supports the following settings: "never" — Never deletes old files. "always" — Checks to delete old files every time Cargo runs. An integer followed by “seconds”, “minutes”, “hours”, “days”, “weeks”, or “months” — Checks to delete old files at most the given time frame. [http] The [http] table defines settings for HTTP behavior. This includes fetching crate dependencies and accessing remote git repositories. http.debug Type: boolean Default: false Environment: CARGO_HTTP_DEBUG If true , enables debugging of HTTP requests. The debug information can be seen by setting the CARGO_LOG=network=debug environment variable (or use network=trace for even more information). Be wary when posting logs from this output in a public location. The output may include headers with authentication tokens which you don’t want to leak! Be sure to review logs before posting them. http.proxy Type: string Default: none Environment: CARGO_HTTP_PROXY or HTTPS_PROXY or https_proxy or http_proxy Sets an HTTP and HTTPS proxy to use. The format is in libcurl format as in [protocol://]host[:port] . If not set, Cargo will also check the http.proxy setting in your global git configuration. If none of those are set, the HTTPS_PROXY or https_proxy environment variables set the proxy for HTTPS requests, and http_proxy sets it for HTTP requests. http.timeout Type: integer Default: 30 Environment: CARGO_HTTP_TIMEOUT or HTTP_TIMEOUT Sets the timeout for each HTTP request, in seconds. http.cainfo Type: string (path) Default: none Environment: CARGO_HTTP_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify TLS certificates. If not specified, Cargo attempts to use the system certificates. http.proxy-cainfo Type: string (path) Default: falls back to http.cainfo if not set Environment: CARGO_HTTP_PROXY_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify proxy TLS certificates. http.check-revoke Type: boolean Default: true (Windows) false (all others) Environment: CARGO_HTTP_CHECK_REVOKE This determines whether or not TLS certificate revocation checks should be performed. This only works on Windows. http.ssl-version Type: string or min/max table Default: none Environment: CARGO_HTTP_SSL_VERSION This sets the minimum TLS version to use. It takes a string, with one of the possible values of "default" , "tlsv1" , "tlsv1.0" , "tlsv1.1" , "tlsv1.2" , or "tlsv1.3" . This may alternatively take a table with two keys, min and max , which each take a string value of the same kind that specifies the minimum and maximum range of TLS versions to use. The default is a minimum version of "tlsv1.0" and a max of the newest version supported on your platform, typically "tlsv1.3" . http.low-speed-limit Type: integer Default: 10 Environment: CARGO_HTTP_LOW_SPEED_LIMIT This setting controls timeout behavior for slow connections. If the average transfer speed in bytes per second is below the given value for http.timeout seconds (default 30 seconds), then the connection is considered too slow and Cargo will abort and retry. http.multiplexing Type: boolean Default: true Environment: CARGO_HTTP_MULTIPLEXING When true , Cargo will attempt to use the HTTP2 protocol with multiplexing. This allows multiple requests to use the same connection, usually improving performance when fetching multiple files. If false , Cargo will use HTTP 1.1 without pipelining. http.user-agent Type: string Default: Cargo’s version Environment: CARGO_HTTP_USER_AGENT Specifies a custom user-agent header to use. The default if not specified is a string that includes Cargo’s version. [install] The [install] table defines defaults for the cargo install command. install.root Type: string (path) Default: Cargo’s home directory Environment: CARGO_INSTALL_ROOT Sets the path to the root directory for installing executables for cargo install . Executables go into a bin directory underneath the root. To track information of installed executables, some extra files, such as .crates.toml and .crates2.json , are also created under this root. The default if not specified is Cargo’s home directory (default .cargo in your home directory). Can be overridden with the --root command-line option. [net] The [net] table controls networking configuration. net.retry Type: integer Default: 3 Environment: CARGO_NET_RETRY Number of times to retry possibly spurious network errors. net.git-fetch-with-cli Type: boolean Default: false Environment: CARGO_NET_GIT_FETCH_WITH_CLI If this is true , then Cargo will use the git executable to fetch registry indexes and git dependencies. If false , then it uses a built-in git library. Setting this to true can be helpful if you have special authentication requirements that Cargo does not support. See Git Authentication for more information about setting up git authentication. net.offline Type: boolean Default: false Environment: CARGO_NET_OFFLINE If this is true , then Cargo will avoid accessing the network, and attempt to proceed with locally cached data. If false , Cargo will access the network as needed, and generate an error if it encounters a network error. Can be overridden with the --offline command-line option. net.ssh The [net.ssh] table contains settings for SSH connections. net.ssh.known-hosts Type: array of strings Default: see description Environment: not supported The known-hosts array contains a list of SSH host keys that should be accepted as valid when connecting to an SSH server (such as for SSH git dependencies). Each entry should be a string in a format similar to OpenSSH known_hosts files. Each string should start with one or more hostnames separated by commas, a space, the key type name, a space, and the base64-encoded key. For example: [net.ssh] known-hosts = [ "example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFO4Q5T0UV0SQevair9PFwoxY9dl4pQl3u5phoqJH3cF" ] Cargo will attempt to load known hosts keys from common locations supported in OpenSSH, and will join those with any listed in a Cargo configuration file. If any matching entry has the correct key, the connection will be allowed. Cargo comes with the host keys for github.com built-in. If those ever change, you can add the new keys to the config or known_hosts file. See Git Authentication for more details. [patch] Just as you can override dependencies using [patch] in Cargo.toml , you can override them in the cargo configuration file to apply those patches to any affected build. The format is identical to the one used in Cargo.toml . Since .cargo/config.toml files are not usually checked into source control, you should prefer patching using Cargo.toml where possible to ensure that other developers can compile your crate in their own environments. Patching through cargo configuration files is generally only appropriate when the patch section is automatically generated by an external build tool. If a given dependency is patched both in a cargo configuration file and a Cargo.toml file, the patch in the configuration file is used. If multiple configuration files patch the same dependency, standard cargo configuration merging is used, which prefers the value defined closest to the current directory, with $HOME/.cargo/config.toml taking the lowest precedence. Relative path dependencies in such a [patch] section are resolved relative to the configuration file they appear in. [profile] The [profile] table can be used to globally change profile settings, and override settings specified in Cargo.toml . It has the same syntax and options as profiles specified in Cargo.toml . See the Profiles chapter for details about the options. [profile.<name>.build-override] Environment: CARGO_PROFILE_<name>_BUILD_OVERRIDE_<key> The build-override table overrides settings for build scripts, proc macros, and their dependencies. It has the same keys as a normal profile. See the overrides section for more details. [profile.<name>.package.<name>] Environment: not supported The package table overrides settings for specific packages. It has the same keys as a normal profile, minus the panic , lto , and rpath settings. See the overrides section for more details. profile.<name>.codegen-units Type: integer Default: See profile docs. Environment: CARGO_PROFILE_<name>_CODEGEN_UNITS See codegen-units . profile.<name>.debug Type: integer or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG See debug . profile.<name>.split-debuginfo Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_SPLIT_DEBUGINFO See split-debuginfo . profile.<name>.debug-assertions Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG_ASSERTIONS See debug-assertions . profile.<name>.incremental Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_INCREMENTAL See incremental . profile.<name>.lto Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_LTO See lto . profile.<name>.overflow-checks Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_OVERFLOW_CHECKS See overflow-checks . profile.<name>.opt-level Type: integer or string Default: See profile docs. Environment: CARGO_PROFILE_<name>_OPT_LEVEL See opt-level . profile.<name>.panic Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_PANIC See panic . profile.<name>.rpath Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_RPATH See rpath . profile.<name>.strip Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_STRIP See strip . [resolver] The [resolver] table overrides dependency resolution behavior for local development (e.g. excludes cargo install ). resolver.incompatible-rust-versions Type: string Default: See resolver docs Environment: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS When resolving which version of a dependency to use, select how versions with incompatible package.rust-version s are treated. Values include: allow : treat rust-version -incompatible versions like any other version fallback : only consider rust-version -incompatible versions if no other version matched Can be overridden with --ignore-rust-version CLI option Setting the dependency’s version requirement higher than any version with a compatible rust-version Specifying the version to cargo update with --precise See the resolver chapter for more details. MSRV: allow is supported on any version fallback is respected as of 1.84 [registries] The [registries] table is used for specifying additional registries . It consists of a sub-table for each named registry. registries.<name>.index Type: string (url) Default: none Environment: CARGO_REGISTRIES_<name>_INDEX Specifies the URL of the index for the registry. registries.<name>.token Type: string Default: none Environment: CARGO_REGISTRIES_<name>_TOKEN Specifies the authentication token for the given registry. This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registries.<name>.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRIES_<name>_CREDENTIAL_PROVIDER Specifies the credential provider for the given registry. If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registries.crates-io.protocol Type: string Default: "sparse" Environment: CARGO_REGISTRIES_CRATES_IO_PROTOCOL Specifies the protocol used to access crates.io. Allowed values are git or sparse . git causes Cargo to clone the entire index of all packages ever published to crates.io from https://github.com/rust-lang/crates.io-index/ . This can have performance implications due to the size of the index. sparse is a newer protocol which uses HTTPS to download only what is necessary from https://index.crates.io/ . This can result in a significant performance improvement for resolving new dependencies in most situations. More information about registry protocols may be found in the Registries chapter . [registry] The [registry] table controls the default registry used when one is not specified. registry.index This value is no longer accepted and should not be used. registry.default Type: string Default: "crates-io" Environment: CARGO_REGISTRY_DEFAULT The name of the registry (from the registries table ) to use by default for registry commands like cargo publish . Can be overridden with the --registry command-line option. registry.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRY_CREDENTIAL_PROVIDER Specifies the credential provider for crates.io . If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registry.token Type: string Default: none Environment: CARGO_REGISTRY_TOKEN Specifies the authentication token for crates.io . This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registry.global-credential-providers Type: array Default: ["cargo:token"] Environment: CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS Specifies the list of global credential providers. If credential provider is not set for a specific registry using registries.<name>.credential-provider , Cargo will use the credential providers in this list. Providers toward the end of the list have precedence. Path and arguments are split on spaces. If the path or arguments contains spaces, the credential provider should be defined in the [credential-alias] table and referenced here by its alias. See Registry Authentication for more information. [source] The [source] table defines the registry sources available. See Source Replacement for more information. It consists of a sub-table for each named source. A source should only define one kind (directory, registry, local-registry, or git). source.<name>.replace-with Type: string Default: none Environment: not supported If set, replace this source with the given named source or named registry. source.<name>.directory Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a directory source. source.<name>.registry Type: string (url) Default: none Environment: not supported Sets the URL to use for a registry source. source.<name>.local-registry Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a local registry source. source.<name>.git Type: string (url) Default: none Environment: not supported Sets the URL to use for a git repository source. source.<name>.branch Type: string Default: none Environment: not supported Sets the branch name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.tag Type: string Default: none Environment: not supported Sets the tag name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.rev Type: string Default: none Environment: not supported Sets the revision to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. [target] The [target] table is used for specifying settings for specific platform targets. It consists of a sub-table which is either a platform triple or a cfg() expression . The given values will be used if the target platform matches either the <triple> value or the <cfg> expression. [target.thumbv7m-none-eabi] linker = "arm-none-eabi-gcc" runner = "my-emulator" rustflags = ["…", "…"] [target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "my-arm-wrapper" rustflags = ["…", "…"] cfg values come from those built-in to the compiler (run rustc --print=cfg to view) and extra --cfg flags passed to rustc (such as those defined in RUSTFLAGS ). Do not try to match on debug_assertions , test , Cargo features like feature="foo" , or values set by build scripts . If using a target spec JSON file, the <triple> value is the filename stem. For example --target foo/bar.json would match [target.bar] . target.<triple>.ar This option is deprecated and unused. target.<triple>.linker Type: string (program path) Default: none Environment: CARGO_TARGET_<triple>_LINKER Specifies the linker which is passed to rustc (via -C linker ) when the <triple> is being compiled for. By default, the linker is not overridden. target.<cfg>.linker This is similar to the target linker , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.runner Type: string or array of strings ( program path with args ) Default: none Environment: CARGO_TARGET_<triple>_RUNNER If a runner is provided, executables for the target <triple> will be executed by invoking the specified runner with the actual executable passed as an argument. This applies to cargo run , cargo test and cargo bench commands. By default, compiled executables are executed directly. target.<cfg>.runner This is similar to the target runner , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.rustflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustflags for more details on the different ways to specific extra flags. target.<cfg>.rustflags This is similar to the target rustflags , but using a cfg() expression . If several <cfg> and <triple> entries match the current target, the flags are joined together. target.<triple>.rustdocflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTDOCFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustdocflags for more details on the different ways to specific extra flags. target.<triple>.<links> The links sub-table provides a way to override a build script . When specified, the build script for the given links library will not be run, and the given values will be used instead. [target.x86_64-unknown-linux-gnu.foo] rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] The [term] table controls terminal output and interaction. term.quiet Type: boolean Default: false Environment: CARGO_TERM_QUIET Controls whether or not log messages are displayed by Cargo. Specifying the --quiet flag will override and force quiet output. Specifying the --verbose flag will override and disable quiet output. term.verbose Type: boolean Default: false Environment: CARGO_TERM_VERBOSE Controls whether or not extra detailed messages are displayed by Cargo. Specifying the --quiet flag will override and disable verbose output. Specifying the --verbose flag will override and force verbose output. term.color Type: string Default: "auto" Environment: CARGO_TERM_COLOR Controls whether or not colored output is used in the terminal. Possible values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. Can be overridden with the --color command-line option. term.hyperlinks Type: bool Default: auto-detect Environment: CARGO_TERM_HYPERLINKS Controls whether or not hyperlinks are used in the terminal. term.unicode Type: bool Default: auto-detect Environment: CARGO_TERM_UNICODE Control whether output can be rendered using non-ASCII unicode characters. term.progress.when Type: string Default: "auto" Environment: CARGO_TERM_PROGRESS_WHEN Controls whether or not progress bar is shown in the terminal. Possible values: auto (default): Intelligently guess whether to show progress bar. always : Always show progress bar. never : Never show progress bar. term.progress.width Type: integer Default: none Environment: CARGO_TERM_PROGRESS_WIDTH Sets the width for progress bar. term.progress.term-integration Type: bool Default: auto-detect Environment: CARGO_TERM_PROGRESS_TERM_INTEGRATION Report progress to the terminal emulator for display in places like the task bar. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---lockfile-path | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://ko-kr.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1RjSBxMAa17aiMTvyn6mz_gSF89_hE51p5kqoCEJgMlWat2M7paWtQ1nJYhNGIO6kTHN--wmrQBfPAP8OMzTye7jkqaK0YJb7-pEr8Hxg7JAJ5N6SM8Y_mShaTqle3ooCbYUoyUeWsD7NT | Facebook Facebook 이메일 또는 휴대폰 비밀번호 계정을 잊으셨나요? 새 계정 만들기 일시적으로 차단됨 일시적으로 차단됨 회원님의 이 기능 사용 속도가 너무 빠른 것 같습니다. 이 기능 사용에서 일시적으로 차단되었습니다. Back 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch 가입하기 로그인 Messenger Facebook Lite 동영상 Meta Pay Meta 스토어 Meta Quest Ray-Ban Meta Meta AI Meta AI 콘텐츠 더 보기 Instagram Threads 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 Meta © 2026 | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/reference/config.html#buildjobs | Configuration - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book Configuration This document explains how Cargo’s configuration system works, as well as available keys or configuration. For configuration of a package through its manifest, see the manifest format . Hierarchical structure Cargo allows local configuration for a particular package as well as global configuration. It looks for configuration files in the current directory and all parent directories. If, for example, Cargo were invoked in /projects/foo/bar/baz , then the following configuration files would be probed for and unified in this order: /projects/foo/bar/baz/.cargo/config.toml /projects/foo/bar/.cargo/config.toml /projects/foo/.cargo/config.toml /projects/.cargo/config.toml /.cargo/config.toml $CARGO_HOME/config.toml which defaults to: Windows: %USERPROFILE%\.cargo\config.toml Unix: $HOME/.cargo/config.toml With this structure, you can specify configuration per-package, and even possibly check it into version control. You can also specify personal defaults with a configuration file in your home directory. If a key is specified in multiple config files, the values will get merged together. Numbers, strings, and booleans will use the value in the deeper config directory taking precedence over ancestor directories, where the home directory is the lowest priority. Arrays will be joined together with higher precedence items being placed later in the merged array. At present, when being invoked from a workspace, Cargo does not read config files from crates within the workspace. i.e. if a workspace has two crates in it, named /projects/foo/bar/baz/mylib and /projects/foo/bar/baz/mybin , and there are Cargo configs at /projects/foo/bar/baz/mylib/.cargo/config.toml and /projects/foo/bar/baz/mybin/.cargo/config.toml , Cargo does not read those configuration files if it is invoked from the workspace root ( /projects/foo/bar/baz/ ). Note: Cargo also reads config files without the .toml extension, such as .cargo/config . Support for the .toml extension was added in version 1.39 and is the preferred form. If both files exist, Cargo will use the file without the extension. Configuration format Configuration files are written in the TOML format (like the manifest), with simple key-value pairs inside of sections (tables). The following is a quick overview of all settings, with detailed descriptions found below. paths = ["/path/to/override"] # path dependency overrides [alias] # command aliases b = "build" c = "check" t = "test" r = "run" rr = "run --release" recursive_example = "rr --example recursions" space_example = ["run", "--release", "--", "\"command list\""] [build] jobs = 1 # number of parallel jobs, defaults to # of CPUs rustc = "rustc" # the rust compiler tool rustc-wrapper = "…" # run this wrapper instead of `rustc` rustc-workspace-wrapper = "…" # run this wrapper instead of `rustc` for workspace members rustdoc = "rustdoc" # the doc generator tool target = "triple" # build for the target triple (ignored by `cargo install`) target-dir = "target" # path of where to place generated artifacts build-dir = "target" # path of where to place intermediate build artifacts rustflags = ["…", "…"] # custom flags to pass to all compiler invocations rustdocflags = ["…", "…"] # custom flags to pass to rustdoc incremental = true # whether or not to enable incremental compilation dep-info-basedir = "…" # path for the base directory for targets in depfiles [credential-alias] # Provides a way to define aliases for credential providers. my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] [doc] browser = "chromium" # browser to use with `cargo doc --open`, # overrides the `BROWSER` environment variable [env] # Set ENV_VAR_NAME=value for any process run by Cargo ENV_VAR_NAME = "value" # Set even if already present in environment ENV_VAR_NAME_2 = { value = "value", force = true } # `value` is relative to the parent of `.cargo/config.toml`, env var will be the full absolute path ENV_VAR_NAME_3 = { value = "relative/path", relative = true } [future-incompat-report] frequency = 'always' # when to display a notification about a future incompat report [cache] auto-clean-frequency = "1 day" # How often to perform automatic cache cleaning [cargo-new] vcs = "none" # VCS to use ('git', 'hg', 'pijul', 'fossil', 'none') [http] debug = false # HTTP debugging proxy = "host:port" # HTTP proxy in libcurl format ssl-version = "tlsv1.3" # TLS version to use ssl-version.max = "tlsv1.3" # maximum TLS version ssl-version.min = "tlsv1.1" # minimum TLS version timeout = 30 # timeout for each HTTP request, in seconds low-speed-limit = 10 # network timeout threshold (bytes/sec) cainfo = "cert.pem" # path to Certificate Authority (CA) bundle proxy-cainfo = "cert.pem" # path to proxy Certificate Authority (CA) bundle check-revoke = true # check for SSL certificate revocation multiplexing = true # HTTP/2 multiplexing user-agent = "…" # the user-agent header [install] root = "/some/path" # `cargo install` destination directory [net] retry = 3 # network retries git-fetch-with-cli = true # use the `git` executable for git operations offline = true # do not access the network [net.ssh] known-hosts = ["..."] # known SSH host keys [patch.<registry>] # Same keys as for [patch] in Cargo.toml [profile.<name>] # Modify profile settings via config. inherits = "dev" # Inherits settings from [profile.dev]. opt-level = 0 # Optimization level. debug = true # Include debug info. split-debuginfo = '...' # Debug info splitting behavior. strip = "none" # Removes symbols or debuginfo. debug-assertions = true # Enables debug assertions. overflow-checks = true # Enables runtime integer overflow checks. lto = false # Sets link-time optimization. panic = 'unwind' # The panic strategy. incremental = true # Incremental compilation. codegen-units = 16 # Number of code generation units. rpath = false # Sets the rpath linking option. [profile.<name>.build-override] # Overrides build-script settings. # Same keys for a normal profile. [profile.<name>.package.<name>] # Override profile for a package. # Same keys for a normal profile (minus `panic`, `lto`, and `rpath`). [resolver] incompatible-rust-versions = "allow" # Specifies how resolver reacts to these [registries.<name>] # registries other than crates.io index = "…" # URL of the registry index token = "…" # authentication token for the registry credential-provider = "cargo:token" # The credential provider for this registry. [registries.crates-io] protocol = "sparse" # The protocol to use to access crates.io. [registry] default = "…" # name of the default registry token = "…" # authentication token for crates.io credential-provider = "cargo:token" # The credential provider for crates.io. global-credential-providers = ["cargo:token"] # The credential providers to use by default. [source.<name>] # source definition and replacement replace-with = "…" # replace this source with the given named source directory = "…" # path to a directory source registry = "…" # URL to a registry source local-registry = "…" # path to a local registry source git = "…" # URL of a git repository source branch = "…" # branch name for the git repository tag = "…" # tag name for the git repository rev = "…" # revision for the git repository [target.<triple>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` rustdocflags = ["…", "…"] # custom flags for `rustdoc` [target.<cfg>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` [target.<triple>.<links>] # `links` build script override rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] quiet = false # whether cargo output is quiet verbose = false # whether cargo provides verbose output color = 'auto' # whether cargo colorizes output hyperlinks = true # whether cargo inserts links into output unicode = true # whether cargo can render output using non-ASCII unicode characters progress.when = 'auto' # whether cargo shows progress bar progress.width = 80 # width of progress bar progress.term-integration = true # whether cargo reports progress to terminal emulator Environment variables Cargo can also be configured through environment variables in addition to the TOML configuration files. For each configuration key of the form foo.bar the environment variable CARGO_FOO_BAR can also be used to define the value. Keys are converted to uppercase, dots and dashes are converted to underscores. For example the target.x86_64-unknown-linux-gnu.runner key can also be defined by the CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER environment variable. Environment variables will take precedence over TOML configuration files. Currently only integer, boolean, string and some array values are supported to be defined by environment variables. Descriptions below indicate which keys support environment variables and otherwise they are not supported due to technical issues . In addition to the system above, Cargo recognizes a few other specific environment variables . Command-line overrides Cargo also accepts arbitrary configuration overrides through the --config command-line option. The argument should be in TOML syntax of KEY=VALUE or provided as a path to an extra configuration file: # With `KEY=VALUE` in TOML syntax cargo --config net.git-fetch-with-cli=true fetch # With a path to a configuration file cargo --config ./path/to/my/extra-config.toml fetch The --config option may be specified multiple times, in which case the values are merged in left-to-right order, using the same merging logic that is used when multiple configuration files apply. Configuration values specified this way take precedence over environment variables, which take precedence over configuration files. When the --config option is provided as an extra configuration file, The configuration file loaded this way follow the same precedence rules as other options specified directly with --config . Some examples of what it looks like using Bourne shell syntax: # Most shells will require escaping. cargo --config http.proxy=\"http://example.com\" … # Spaces may be used. cargo --config "net.git-fetch-with-cli = true" … # TOML array example. Single quotes make it easier to read and write. cargo --config 'build.rustdocflags = ["--html-in-header", "header.html"]' … # Example of a complex TOML key. cargo --config "target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))'.runner = 'my-runner'" … # Example of overriding a profile setting. cargo --config profile.dev.package.image.opt-level=3 … Config-relative paths Paths in config files may be absolute, relative, or a bare name without any path separators. Paths for executables without a path separator will use the PATH environment variable to search for the executable. Paths for non-executables will be relative to where the config value is defined. In particular, rules are: For environment variables, paths are relative to the current working directory. For config values loaded directly from the --config KEY=VALUE option, paths are relative to the current working directory. For config files, paths are relative to the parent directory of the directory where the config files were defined, no matter those files are from either the hierarchical probing or the --config <path> option. Note: To maintain consistency with existing .cargo/config.toml probing behavior, it is by design that a path in a config file passed via --config <path> is also relative to two levels up from the config file itself. To avoid unexpected results, the rule of thumb is putting your extra config files at the same level of discovered .cargo/config.toml in your project. For instance, given a project /my/project , it is recommended to put config files under /my/project/.cargo or a new directory at the same level, such as /my/project/.config . # Relative path examples. [target.x86_64-unknown-linux-gnu] runner = "foo" # Searches `PATH` for `foo`. [source.vendored-sources] # Directory is relative to the parent where `.cargo/config.toml` is located. # For example, `/my/project/.cargo/config.toml` would result in `/my/project/vendor`. directory = "vendor" Executable paths with arguments Some Cargo commands invoke external programs, which can be configured as a path and some number of arguments. The value may be an array of strings like ['/path/to/program', 'somearg'] or a space-separated string like '/path/to/program somearg' . If the path to the executable contains a space, the list form must be used. If Cargo is passing other arguments to the program such as a path to open or run, they will be passed after the last specified argument in the value of an option of this format. If the specified program does not have path separators, Cargo will search PATH for its executable. Credentials Configuration values with sensitive information are stored in the $CARGO_HOME/credentials.toml file. This file is automatically created and updated by cargo login and cargo logout when using the cargo:token credential provider. Tokens are used by some Cargo commands such as cargo publish for authenticating with remote registries. Care should be taken to protect the tokens and to keep them secret. It follows the same format as Cargo config files. [registry] token = "…" # Access token for crates.io [registries.<name>] token = "…" # Access token for the named registry As with most other config values, tokens may be specified with environment variables. The token for crates.io may be specified with the CARGO_REGISTRY_TOKEN environment variable. Tokens for other registries may be specified with environment variables of the form CARGO_REGISTRIES_<name>_TOKEN where <name> is the name of the registry in all capital letters. Note: Cargo also reads and writes credential files without the .toml extension, such as .cargo/credentials . Support for the .toml extension was added in version 1.39. In version 1.68, Cargo writes to the file with the extension by default. However, for backward compatibility reason, when both files exist, Cargo will read and write the file without the extension. Configuration keys This section documents all configuration keys. The description for keys with variable parts are annotated with angled brackets like target.<triple> where the <triple> part can be any target triple like target.x86_64-pc-windows-msvc . paths Type: array of strings (paths) Default: none Environment: not supported An array of paths to local packages which are to be used as overrides for dependencies. For more information see the Overriding Dependencies guide . [alias] Type: string or array of strings Default: see below Environment: CARGO_ALIAS_<name> The [alias] table defines CLI command aliases. For example, running cargo b is an alias for running cargo build . Each key in the table is the subcommand, and the value is the actual command to run. The value may be an array of strings, where the first element is the command and the following are arguments. It may also be a string, which will be split on spaces into subcommand and arguments. The following aliases are built-in to Cargo: [alias] b = "build" c = "check" d = "doc" t = "test" r = "run" rm = "remove" Aliases are not allowed to redefine existing built-in commands. Aliases are recursive: [alias] rr = "run --release" recursive_example = "rr --example recursions" [build] The [build] table controls build-time operations and compiler settings. build.jobs Type: integer or string Default: number of logical CPUs Environment: CARGO_BUILD_JOBS Sets the maximum number of compiler processes to run in parallel. If negative, it sets the maximum number of compiler processes to the number of logical CPUs plus provided value. Should not be 0. If a string default is provided, it sets the value back to defaults. Can be overridden with the --jobs CLI option. build.rustc Type: string (program path) Default: "rustc" Environment: CARGO_BUILD_RUSTC or RUSTC Sets the executable to use for rustc . build.rustc-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WRAPPER or RUSTC_WRAPPER Sets a wrapper to execute instead of rustc . The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). build.rustc-workspace-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER or RUSTC_WORKSPACE_WRAPPER Sets a wrapper to execute instead of rustc , for workspace members only. When building a single-package project without workspaces, that package is considered to be the workspace. The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). It affects the filename hash so that artifacts produced by the wrapper are cached separately. If both rustc-wrapper and rustc-workspace-wrapper are set, then they will be nested: the final invocation is $RUSTC_WRAPPER $RUSTC_WORKSPACE_WRAPPER $RUSTC . build.rustdoc Type: string (program path) Default: "rustdoc" Environment: CARGO_BUILD_RUSTDOC or RUSTDOC Sets the executable to use for rustdoc . build.target Type: string or array of strings Default: host platform Environment: CARGO_BUILD_TARGET The default target platform triples to compile to. Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. Can be overridden with the --target CLI option. [build] target = ["x86_64-unknown-linux-gnu", "i686-unknown-linux-gnu"] build.target-dir Type: string (path) Default: "target" Environment: CARGO_BUILD_TARGET_DIR or CARGO_TARGET_DIR The path to where all compiler output is placed. The default if not specified is a directory named target located at the root of the workspace. Can be overridden with the --target-dir CLI option. For more information see the build cache documentation . build.build-dir Type: string (path) Default: Defaults to the value of build.target-dir Environment: CARGO_BUILD_BUILD_DIR The directory where intermediate build artifacts will be stored. Intermediate artifacts are produced by Rustc/Cargo during the build process. This option supports path templating. Available template variables: {workspace-root} resolves to root of the current workspace. {cargo-cache-home} resolves to CARGO_HOME {workspace-path-hash} resolves to a hash of the manifest path For more information see the build cache documentation . build.rustflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS or RUSTFLAGS Extra command-line flags to pass to rustc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTFLAGS environment variable. RUSTFLAGS environment variable. All matching target.<triple>.rustflags and target.<cfg>.rustflags config entries joined together. build.rustflags config value. Additional flags may also be passed with the cargo rustc command. If the --target flag (or build.target ) is used, then the flags will only be passed to the compiler for the target. Things being built for the host, such as build scripts or proc macros, will not receive the args. Without --target , the flags will be passed to all compiler invocations (including build scripts and proc macros) because dependencies are shared. If you have args that you do not want to pass to build scripts or proc macros and are building for the host, pass --target with the host triple . It is not recommended to pass in flags that Cargo itself usually manages. For example, the flags driven by profiles are best handled by setting the appropriate profile setting. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.rustdocflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTDOCFLAGS or CARGO_ENCODED_RUSTDOCFLAGS or RUSTDOCFLAGS Extra command-line flags to pass to rustdoc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTDOCFLAGS environment variable. RUSTDOCFLAGS environment variable. All matching target.<triple>.rustdocflags config entries joined together. build.rustdocflags config value. Additional flags may also be passed with the cargo rustdoc command. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.incremental Type: bool Default: from profile Environment: CARGO_BUILD_INCREMENTAL or CARGO_INCREMENTAL Whether or not to perform incremental compilation . The default if not set is to use the value from the profile . Otherwise this overrides the setting of all profiles. The CARGO_INCREMENTAL environment variable can be set to 1 to force enable incremental compilation for all profiles, or 0 to disable it. This env var overrides the config setting. build.dep-info-basedir Type: string (path) Default: none Environment: CARGO_BUILD_DEP_INFO_BASEDIR Strips the given path prefix from dep info file paths. This config setting is intended to convert absolute paths to relative paths for tools that require relative paths. The setting itself is a config-relative path. So, for example, a value of "." would strip all paths starting with the parent directory of the .cargo directory. build.pipelining This option is deprecated and unused. Cargo always has pipelining enabled. [credential-alias] Type: string or array of strings Default: empty Environment: CARGO_CREDENTIAL_ALIAS_<name> The [credential-alias] table defines credential provider aliases. These aliases can be referenced as an element of the registry.global-credential-providers array, or as a credential provider for a specific registry under registries.<NAME>.credential-provider . If specified as a string, the value will be split on spaces into path and arguments. For example, to define an alias called my-alias : [credential-alias] my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] See Registry Authentication for more information. [doc] The [doc] table defines options for the cargo doc command. doc.browser Type: string or array of strings ( program path with args ) Default: BROWSER environment variable, or, if that is missing, opening the link in a system specific way This option sets the browser to be used by cargo doc , overriding the BROWSER environment variable when opening documentation with the --open option. [cargo-new] The [cargo-new] table defines defaults for the cargo new command. cargo-new.name This option is deprecated and unused. cargo-new.email This option is deprecated and unused. cargo-new.vcs Type: string Default: "git" or "none" Environment: CARGO_CARGO_NEW_VCS Specifies the source control system to use for initializing a new repository. Valid values are git , hg (for Mercurial), pijul , fossil or none to disable this behavior. Defaults to git , or none if already inside a VCS repository. Can be overridden with the --vcs CLI option. [env] The [env] section allows you to set additional environment variables for build scripts, rustc invocations, cargo run and cargo build . [env] OPENSSL_DIR = "/opt/openssl" By default, the variables specified will not override values that already exist in the environment. This behavior can be changed by setting the force flag. Setting the relative flag evaluates the value as a config-relative path that is relative to the parent directory of the .cargo directory that contains the config.toml file. The value of the environment variable will be the full absolute path. [env] TMPDIR = { value = "/home/tmp", force = true } OPENSSL_DIR = { value = "vendor/openssl", relative = true } [future-incompat-report] The [future-incompat-report] table controls setting for future incompat reporting future-incompat-report.frequency Type: string Default: "always" Environment: CARGO_FUTURE_INCOMPAT_REPORT_FREQUENCY Controls how often we display a notification to the terminal when a future incompat report is available. Possible values: always (default): Always display a notification when a command (e.g. cargo build ) produces a future incompat report never : Never display a notification [cache] The [cache] table defines settings for cargo’s caches. Global caches When running cargo commands, Cargo will automatically track which files you are using within the global cache. Periodically, Cargo will delete files that have not been used for some period of time. It will delete files that have to be downloaded from the network if they have not been used in 3 months. Files that can be generated without network access will be deleted if they have not been used in 1 month. The automatic deletion of files only occurs when running commands that are already doing a significant amount of work, such as all of the build commands ( cargo build , cargo test , cargo check , etc.), and cargo fetch . Automatic deletion is disabled if cargo is offline such as with --offline or --frozen to avoid deleting artifacts that may need to be used if you are offline for a long period of time. Note : This tracking is currently only implemented for the global cache in Cargo’s home directory. This includes registry indexes and source files downloaded from registries and git dependencies. Support for tracking build artifacts is not yet implemented, and tracked in cargo#13136 . Additionally, there is an unstable feature to support manually triggering cache cleaning, and to further customize the configuration options. See the Unstable chapter for more information. cache.auto-clean-frequency Type: string Default: "1 day" Environment: CARGO_CACHE_AUTO_CLEAN_FREQUENCY This option defines how often Cargo will automatically delete unused files in the global cache. This does not define how old the files must be, those thresholds are described above . It supports the following settings: "never" — Never deletes old files. "always" — Checks to delete old files every time Cargo runs. An integer followed by “seconds”, “minutes”, “hours”, “days”, “weeks”, or “months” — Checks to delete old files at most the given time frame. [http] The [http] table defines settings for HTTP behavior. This includes fetching crate dependencies and accessing remote git repositories. http.debug Type: boolean Default: false Environment: CARGO_HTTP_DEBUG If true , enables debugging of HTTP requests. The debug information can be seen by setting the CARGO_LOG=network=debug environment variable (or use network=trace for even more information). Be wary when posting logs from this output in a public location. The output may include headers with authentication tokens which you don’t want to leak! Be sure to review logs before posting them. http.proxy Type: string Default: none Environment: CARGO_HTTP_PROXY or HTTPS_PROXY or https_proxy or http_proxy Sets an HTTP and HTTPS proxy to use. The format is in libcurl format as in [protocol://]host[:port] . If not set, Cargo will also check the http.proxy setting in your global git configuration. If none of those are set, the HTTPS_PROXY or https_proxy environment variables set the proxy for HTTPS requests, and http_proxy sets it for HTTP requests. http.timeout Type: integer Default: 30 Environment: CARGO_HTTP_TIMEOUT or HTTP_TIMEOUT Sets the timeout for each HTTP request, in seconds. http.cainfo Type: string (path) Default: none Environment: CARGO_HTTP_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify TLS certificates. If not specified, Cargo attempts to use the system certificates. http.proxy-cainfo Type: string (path) Default: falls back to http.cainfo if not set Environment: CARGO_HTTP_PROXY_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify proxy TLS certificates. http.check-revoke Type: boolean Default: true (Windows) false (all others) Environment: CARGO_HTTP_CHECK_REVOKE This determines whether or not TLS certificate revocation checks should be performed. This only works on Windows. http.ssl-version Type: string or min/max table Default: none Environment: CARGO_HTTP_SSL_VERSION This sets the minimum TLS version to use. It takes a string, with one of the possible values of "default" , "tlsv1" , "tlsv1.0" , "tlsv1.1" , "tlsv1.2" , or "tlsv1.3" . This may alternatively take a table with two keys, min and max , which each take a string value of the same kind that specifies the minimum and maximum range of TLS versions to use. The default is a minimum version of "tlsv1.0" and a max of the newest version supported on your platform, typically "tlsv1.3" . http.low-speed-limit Type: integer Default: 10 Environment: CARGO_HTTP_LOW_SPEED_LIMIT This setting controls timeout behavior for slow connections. If the average transfer speed in bytes per second is below the given value for http.timeout seconds (default 30 seconds), then the connection is considered too slow and Cargo will abort and retry. http.multiplexing Type: boolean Default: true Environment: CARGO_HTTP_MULTIPLEXING When true , Cargo will attempt to use the HTTP2 protocol with multiplexing. This allows multiple requests to use the same connection, usually improving performance when fetching multiple files. If false , Cargo will use HTTP 1.1 without pipelining. http.user-agent Type: string Default: Cargo’s version Environment: CARGO_HTTP_USER_AGENT Specifies a custom user-agent header to use. The default if not specified is a string that includes Cargo’s version. [install] The [install] table defines defaults for the cargo install command. install.root Type: string (path) Default: Cargo’s home directory Environment: CARGO_INSTALL_ROOT Sets the path to the root directory for installing executables for cargo install . Executables go into a bin directory underneath the root. To track information of installed executables, some extra files, such as .crates.toml and .crates2.json , are also created under this root. The default if not specified is Cargo’s home directory (default .cargo in your home directory). Can be overridden with the --root command-line option. [net] The [net] table controls networking configuration. net.retry Type: integer Default: 3 Environment: CARGO_NET_RETRY Number of times to retry possibly spurious network errors. net.git-fetch-with-cli Type: boolean Default: false Environment: CARGO_NET_GIT_FETCH_WITH_CLI If this is true , then Cargo will use the git executable to fetch registry indexes and git dependencies. If false , then it uses a built-in git library. Setting this to true can be helpful if you have special authentication requirements that Cargo does not support. See Git Authentication for more information about setting up git authentication. net.offline Type: boolean Default: false Environment: CARGO_NET_OFFLINE If this is true , then Cargo will avoid accessing the network, and attempt to proceed with locally cached data. If false , Cargo will access the network as needed, and generate an error if it encounters a network error. Can be overridden with the --offline command-line option. net.ssh The [net.ssh] table contains settings for SSH connections. net.ssh.known-hosts Type: array of strings Default: see description Environment: not supported The known-hosts array contains a list of SSH host keys that should be accepted as valid when connecting to an SSH server (such as for SSH git dependencies). Each entry should be a string in a format similar to OpenSSH known_hosts files. Each string should start with one or more hostnames separated by commas, a space, the key type name, a space, and the base64-encoded key. For example: [net.ssh] known-hosts = [ "example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFO4Q5T0UV0SQevair9PFwoxY9dl4pQl3u5phoqJH3cF" ] Cargo will attempt to load known hosts keys from common locations supported in OpenSSH, and will join those with any listed in a Cargo configuration file. If any matching entry has the correct key, the connection will be allowed. Cargo comes with the host keys for github.com built-in. If those ever change, you can add the new keys to the config or known_hosts file. See Git Authentication for more details. [patch] Just as you can override dependencies using [patch] in Cargo.toml , you can override them in the cargo configuration file to apply those patches to any affected build. The format is identical to the one used in Cargo.toml . Since .cargo/config.toml files are not usually checked into source control, you should prefer patching using Cargo.toml where possible to ensure that other developers can compile your crate in their own environments. Patching through cargo configuration files is generally only appropriate when the patch section is automatically generated by an external build tool. If a given dependency is patched both in a cargo configuration file and a Cargo.toml file, the patch in the configuration file is used. If multiple configuration files patch the same dependency, standard cargo configuration merging is used, which prefers the value defined closest to the current directory, with $HOME/.cargo/config.toml taking the lowest precedence. Relative path dependencies in such a [patch] section are resolved relative to the configuration file they appear in. [profile] The [profile] table can be used to globally change profile settings, and override settings specified in Cargo.toml . It has the same syntax and options as profiles specified in Cargo.toml . See the Profiles chapter for details about the options. [profile.<name>.build-override] Environment: CARGO_PROFILE_<name>_BUILD_OVERRIDE_<key> The build-override table overrides settings for build scripts, proc macros, and their dependencies. It has the same keys as a normal profile. See the overrides section for more details. [profile.<name>.package.<name>] Environment: not supported The package table overrides settings for specific packages. It has the same keys as a normal profile, minus the panic , lto , and rpath settings. See the overrides section for more details. profile.<name>.codegen-units Type: integer Default: See profile docs. Environment: CARGO_PROFILE_<name>_CODEGEN_UNITS See codegen-units . profile.<name>.debug Type: integer or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG See debug . profile.<name>.split-debuginfo Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_SPLIT_DEBUGINFO See split-debuginfo . profile.<name>.debug-assertions Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG_ASSERTIONS See debug-assertions . profile.<name>.incremental Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_INCREMENTAL See incremental . profile.<name>.lto Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_LTO See lto . profile.<name>.overflow-checks Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_OVERFLOW_CHECKS See overflow-checks . profile.<name>.opt-level Type: integer or string Default: See profile docs. Environment: CARGO_PROFILE_<name>_OPT_LEVEL See opt-level . profile.<name>.panic Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_PANIC See panic . profile.<name>.rpath Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_RPATH See rpath . profile.<name>.strip Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_STRIP See strip . [resolver] The [resolver] table overrides dependency resolution behavior for local development (e.g. excludes cargo install ). resolver.incompatible-rust-versions Type: string Default: See resolver docs Environment: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS When resolving which version of a dependency to use, select how versions with incompatible package.rust-version s are treated. Values include: allow : treat rust-version -incompatible versions like any other version fallback : only consider rust-version -incompatible versions if no other version matched Can be overridden with --ignore-rust-version CLI option Setting the dependency’s version requirement higher than any version with a compatible rust-version Specifying the version to cargo update with --precise See the resolver chapter for more details. MSRV: allow is supported on any version fallback is respected as of 1.84 [registries] The [registries] table is used for specifying additional registries . It consists of a sub-table for each named registry. registries.<name>.index Type: string (url) Default: none Environment: CARGO_REGISTRIES_<name>_INDEX Specifies the URL of the index for the registry. registries.<name>.token Type: string Default: none Environment: CARGO_REGISTRIES_<name>_TOKEN Specifies the authentication token for the given registry. This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registries.<name>.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRIES_<name>_CREDENTIAL_PROVIDER Specifies the credential provider for the given registry. If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registries.crates-io.protocol Type: string Default: "sparse" Environment: CARGO_REGISTRIES_CRATES_IO_PROTOCOL Specifies the protocol used to access crates.io. Allowed values are git or sparse . git causes Cargo to clone the entire index of all packages ever published to crates.io from https://github.com/rust-lang/crates.io-index/ . This can have performance implications due to the size of the index. sparse is a newer protocol which uses HTTPS to download only what is necessary from https://index.crates.io/ . This can result in a significant performance improvement for resolving new dependencies in most situations. More information about registry protocols may be found in the Registries chapter . [registry] The [registry] table controls the default registry used when one is not specified. registry.index This value is no longer accepted and should not be used. registry.default Type: string Default: "crates-io" Environment: CARGO_REGISTRY_DEFAULT The name of the registry (from the registries table ) to use by default for registry commands like cargo publish . Can be overridden with the --registry command-line option. registry.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRY_CREDENTIAL_PROVIDER Specifies the credential provider for crates.io . If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registry.token Type: string Default: none Environment: CARGO_REGISTRY_TOKEN Specifies the authentication token for crates.io . This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registry.global-credential-providers Type: array Default: ["cargo:token"] Environment: CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS Specifies the list of global credential providers. If credential provider is not set for a specific registry using registries.<name>.credential-provider , Cargo will use the credential providers in this list. Providers toward the end of the list have precedence. Path and arguments are split on spaces. If the path or arguments contains spaces, the credential provider should be defined in the [credential-alias] table and referenced here by its alias. See Registry Authentication for more information. [source] The [source] table defines the registry sources available. See Source Replacement for more information. It consists of a sub-table for each named source. A source should only define one kind (directory, registry, local-registry, or git). source.<name>.replace-with Type: string Default: none Environment: not supported If set, replace this source with the given named source or named registry. source.<name>.directory Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a directory source. source.<name>.registry Type: string (url) Default: none Environment: not supported Sets the URL to use for a registry source. source.<name>.local-registry Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a local registry source. source.<name>.git Type: string (url) Default: none Environment: not supported Sets the URL to use for a git repository source. source.<name>.branch Type: string Default: none Environment: not supported Sets the branch name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.tag Type: string Default: none Environment: not supported Sets the tag name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.rev Type: string Default: none Environment: not supported Sets the revision to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. [target] The [target] table is used for specifying settings for specific platform targets. It consists of a sub-table which is either a platform triple or a cfg() expression . The given values will be used if the target platform matches either the <triple> value or the <cfg> expression. [target.thumbv7m-none-eabi] linker = "arm-none-eabi-gcc" runner = "my-emulator" rustflags = ["…", "…"] [target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "my-arm-wrapper" rustflags = ["…", "…"] cfg values come from those built-in to the compiler (run rustc --print=cfg to view) and extra --cfg flags passed to rustc (such as those defined in RUSTFLAGS ). Do not try to match on debug_assertions , test , Cargo features like feature="foo" , or values set by build scripts . If using a target spec JSON file, the <triple> value is the filename stem. For example --target foo/bar.json would match [target.bar] . target.<triple>.ar This option is deprecated and unused. target.<triple>.linker Type: string (program path) Default: none Environment: CARGO_TARGET_<triple>_LINKER Specifies the linker which is passed to rustc (via -C linker ) when the <triple> is being compiled for. By default, the linker is not overridden. target.<cfg>.linker This is similar to the target linker , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.runner Type: string or array of strings ( program path with args ) Default: none Environment: CARGO_TARGET_<triple>_RUNNER If a runner is provided, executables for the target <triple> will be executed by invoking the specified runner with the actual executable passed as an argument. This applies to cargo run , cargo test and cargo bench commands. By default, compiled executables are executed directly. target.<cfg>.runner This is similar to the target runner , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.rustflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustflags for more details on the different ways to specific extra flags. target.<cfg>.rustflags This is similar to the target rustflags , but using a cfg() expression . If several <cfg> and <triple> entries match the current target, the flags are joined together. target.<triple>.rustdocflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTDOCFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustdocflags for more details on the different ways to specific extra flags. target.<triple>.<links> The links sub-table provides a way to override a build script . When specified, the build script for the given links library will not be run, and the given values will be used instead. [target.x86_64-unknown-linux-gnu.foo] rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] The [term] table controls terminal output and interaction. term.quiet Type: boolean Default: false Environment: CARGO_TERM_QUIET Controls whether or not log messages are displayed by Cargo. Specifying the --quiet flag will override and force quiet output. Specifying the --verbose flag will override and disable quiet output. term.verbose Type: boolean Default: false Environment: CARGO_TERM_VERBOSE Controls whether or not extra detailed messages are displayed by Cargo. Specifying the --quiet flag will override and disable verbose output. Specifying the --verbose flag will override and force verbose output. term.color Type: string Default: "auto" Environment: CARGO_TERM_COLOR Controls whether or not colored output is used in the terminal. Possible values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. Can be overridden with the --color command-line option. term.hyperlinks Type: bool Default: auto-detect Environment: CARGO_TERM_HYPERLINKS Controls whether or not hyperlinks are used in the terminal. term.unicode Type: bool Default: auto-detect Environment: CARGO_TERM_UNICODE Control whether output can be rendered using non-ASCII unicode characters. term.progress.when Type: string Default: "auto" Environment: CARGO_TERM_PROGRESS_WHEN Controls whether or not progress bar is shown in the terminal. Possible values: auto (default): Intelligently guess whether to show progress bar. always : Always show progress bar. never : Never show progress bar. term.progress.width Type: integer Default: none Environment: CARGO_TERM_PROGRESS_WIDTH Sets the width for progress bar. term.progress.term-integration Type: bool Default: auto-detect Environment: CARGO_TERM_PROGRESS_TERM_INTEGRATION Report progress to the terminal emulator for display in places like the task bar. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#synopsis | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#name | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#examples-of-error-messages | Interoperability - Rust API Guidelines About Checklist 1. Naming 2. Interoperability 3. Macros 4. Documentation 5. Predictability 6. Flexibility 7. Type safety 8. Dependability 9. Debuggability 10. Future proofing 11. Necessities External links Light (default) Rust Coal Navy Ayu Rust API Guidelines Interoperability Types eagerly implement common traits (C-COMMON-TRAITS) Rust's trait system does not allow orphans : roughly, every impl must live either in the crate that defines the trait or the implementing type. Consequently, crates that define new types should eagerly implement all applicable, common traits. To see why, consider the following situation: Crate std defines trait Display . Crate url defines type Url , without implementing Display . Crate webapp imports from both std and url , There is no way for webapp to add Display to Url , since it defines neither. (Note: the newtype pattern can provide an efficient, but inconvenient workaround.) The most important common traits to implement from std are: Copy Clone Eq PartialEq Ord PartialOrd Hash Debug Display Default Note that it is common and expected for types to implement both Default and an empty new constructor. new is the constructor convention in Rust, and users expect it to exist, so if it is reasonable for the basic constructor to take no arguments, then it should, even if it is functionally identical to default . Conversions use the standard traits From , AsRef , AsMut (C-CONV-TRAITS) The following conversion traits should be implemented where it makes sense: From TryFrom AsRef AsMut The following conversion traits should never be implemented: Into TryInto These traits have a blanket impl based on From and TryFrom . Implement those instead. Examples from the standard library From<u16> is implemented for u32 because a smaller integer can always be converted to a bigger integer. From<u32> is not implemented for u16 because the conversion may not be possible if the integer is too big. TryFrom<u32> is implemented for u16 and returns an error if the integer is too big to fit in u16 . From<Ipv6Addr> is implemented for IpAddr , which is a type that can represent both v4 and v6 IP addresses. Collections implement FromIterator and Extend (C-COLLECT) FromIterator and Extend enable collections to be used conveniently with the following iterator methods: Iterator::collect Iterator::partition Iterator::unzip FromIterator is for creating a new collection containing items from an iterator, and Extend is for adding items from an iterator onto an existing collection. Examples from the standard library Vec<T> implements both FromIterator<T> and Extend<T> . Data structures implement Serde's Serialize , Deserialize (C-SERDE) Types that play the role of a data structure should implement Serialize and Deserialize . There is a continuum of types between things that are clearly a data structure and things that are clearly not, with gray area in between. LinkedHashMap and IpAddr are data structures. It would be completely reasonable for somebody to want to read in a LinkedHashMap or IpAddr from a JSON file, or send one over IPC to another process. LittleEndian is not a data structure. It is a marker used by the byteorder crate to optimize at compile time for bytes in a particular order, and in fact an instance of LittleEndian can never exist at runtime. So these are clear-cut examples; the #rust or #serde IRC channels can help assess more ambiguous cases if necessary. If a crate does not already depend on Serde for other reasons, it may wish to gate Serde impls behind a Cargo cfg. This way downstream libraries only need to pay the cost of compiling Serde if they need those impls to exist. For consistency with other Serde-based libraries, the name of the Cargo cfg should be simply "serde" . Do not use a different name for the cfg like "serde_impls" or "serde_serialization" . The canonical implementation looks like this when not using derive: [dependencies] serde = { version = "1.0", optional = true } #![allow(unused)] fn main() { pub struct T { /* ... */ } #[cfg(feature = "serde")] impl Serialize for T { /* ... */ } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for T { /* ... */ } } And when using derive: [dependencies] serde = { version = "1.0", optional = true, features = ["derive"] } #![allow(unused)] fn main() { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct T { /* ... */ } } Types are Send and Sync where possible (C-SEND-SYNC) Send and Sync are automatically implemented when the compiler determines it is appropriate. In types that manipulate raw pointers, be vigilant that the Send and Sync status of your type accurately reflects its thread safety characteristics. Tests like the following can help catch unintentional regressions in whether the type implements Send or Sync . #![allow(unused)] fn main() { #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<MyStrangeType>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<MyStrangeType>(); } } Error types are meaningful and well-behaved (C-GOOD-ERR) An error type is any type E used in a Result<T, E> returned by any public function of your crate. Error types should always implement the std::error::Error trait which is the mechanism by which error handling libraries like error-chain abstract over different types of errors, and which allows the error to be used as the source() of another error. Additionally, error types should implement the Send and Sync traits. An error that is not Send cannot be returned by a thread run with thread::spawn . An error that is not Sync cannot be passed across threads using an Arc . These are common requirements for basic error handling in a multithreaded application. Send and Sync are also important for being able to package a custom error into an IO error using std::io::Error::new , which requires a trait bound of Error + Send + Sync . One place to be vigilant about this guideline is in functions that return Error trait objects, for example reqwest::Error::get_ref . Typically Error + Send + Sync + 'static will be the most useful for callers. The addition of 'static allows the trait object to be used with Error::downcast_ref . Never use () as an error type, even where there is no useful additional information for the error to carry. () does not implement Error so it cannot be used with error handling libraries like error-chain . () does not implement Display so a user would need to write an error message of their own if they want to fail because of the error. () has an unhelpful Debug representation for users that decide to unwrap() the error. It would not be semantically meaningful for a downstream library to implement From<()> for their error type, so () as an error type cannot be used with the ? operator. Instead, define a meaningful error type specific to your crate or to the individual function. Provide appropriate Error and Display impls. If there is no useful information for the error to carry, it can be implemented as a unit struct. #![allow(unused)] fn main() { use std::error::Error; use std::fmt::Display; // Instead of this... fn do_the_thing() -> Result<Wow, ()> // Prefer this... fn do_the_thing() -> Result<Wow, DoError> #[derive(Debug)] struct DoError; impl Display for DoError { /* ... */ } impl Error for DoError { /* ... */ } } The error message given by the Display representation of an error type should be lowercase without trailing punctuation, and typically concise. Error::description() should not be implemented. It has been deprecated and users should always use Display instead of description() to print the error. Examples from the standard library ParseBoolError is returned when failing to parse a bool from a string. Examples of error messages "unexpected end of file" "provided string was not `true` or `false`" "invalid IP address syntax" "second time provided was later than self" "invalid UTF-8 sequence of {} bytes from index {}" "environment variable was not valid unicode: {:?}" Binary number types provide Hex , Octal , Binary formatting (C-NUM-FMT) std::fmt::UpperHex std::fmt::LowerHex std::fmt::Octal std::fmt::Binary These traits control the representation of a type under the {:X} , {:x} , {:o} , and {:b} format specifiers. Implement these traits for any number type on which you would consider doing bitwise manipulations like | or & . This is especially appropriate for bitflag types. Numeric quantity types like struct Nanoseconds(u64) probably do not need these. Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE) The standard library contains these two impls: #![allow(unused)] fn main() { impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ } impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ } } That means any function that accepts R: Read or W: Write generic parameters by value can be called with a mut reference if necessary. In the documentation of such functions, briefly remind users that a mut reference can be passed. New Rust users often struggle with this. They may have opened a file and want to read multiple pieces of data out of it, but the function to read one piece consumes the reader by value, so they are stuck. The solution would be to leverage one of the above impls and pass &mut f instead of f as the reader parameter. Examples flate2::read::GzDecoder::new flate2::write::GzEncoder::new serde_json::from_reader serde_json::to_writer | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#types-eagerly-implement-common-traits-c-common-traits | Interoperability - Rust API Guidelines About Checklist 1. Naming 2. Interoperability 3. Macros 4. Documentation 5. Predictability 6. Flexibility 7. Type safety 8. Dependability 9. Debuggability 10. Future proofing 11. Necessities External links Light (default) Rust Coal Navy Ayu Rust API Guidelines Interoperability Types eagerly implement common traits (C-COMMON-TRAITS) Rust's trait system does not allow orphans : roughly, every impl must live either in the crate that defines the trait or the implementing type. Consequently, crates that define new types should eagerly implement all applicable, common traits. To see why, consider the following situation: Crate std defines trait Display . Crate url defines type Url , without implementing Display . Crate webapp imports from both std and url , There is no way for webapp to add Display to Url , since it defines neither. (Note: the newtype pattern can provide an efficient, but inconvenient workaround.) The most important common traits to implement from std are: Copy Clone Eq PartialEq Ord PartialOrd Hash Debug Display Default Note that it is common and expected for types to implement both Default and an empty new constructor. new is the constructor convention in Rust, and users expect it to exist, so if it is reasonable for the basic constructor to take no arguments, then it should, even if it is functionally identical to default . Conversions use the standard traits From , AsRef , AsMut (C-CONV-TRAITS) The following conversion traits should be implemented where it makes sense: From TryFrom AsRef AsMut The following conversion traits should never be implemented: Into TryInto These traits have a blanket impl based on From and TryFrom . Implement those instead. Examples from the standard library From<u16> is implemented for u32 because a smaller integer can always be converted to a bigger integer. From<u32> is not implemented for u16 because the conversion may not be possible if the integer is too big. TryFrom<u32> is implemented for u16 and returns an error if the integer is too big to fit in u16 . From<Ipv6Addr> is implemented for IpAddr , which is a type that can represent both v4 and v6 IP addresses. Collections implement FromIterator and Extend (C-COLLECT) FromIterator and Extend enable collections to be used conveniently with the following iterator methods: Iterator::collect Iterator::partition Iterator::unzip FromIterator is for creating a new collection containing items from an iterator, and Extend is for adding items from an iterator onto an existing collection. Examples from the standard library Vec<T> implements both FromIterator<T> and Extend<T> . Data structures implement Serde's Serialize , Deserialize (C-SERDE) Types that play the role of a data structure should implement Serialize and Deserialize . There is a continuum of types between things that are clearly a data structure and things that are clearly not, with gray area in between. LinkedHashMap and IpAddr are data structures. It would be completely reasonable for somebody to want to read in a LinkedHashMap or IpAddr from a JSON file, or send one over IPC to another process. LittleEndian is not a data structure. It is a marker used by the byteorder crate to optimize at compile time for bytes in a particular order, and in fact an instance of LittleEndian can never exist at runtime. So these are clear-cut examples; the #rust or #serde IRC channels can help assess more ambiguous cases if necessary. If a crate does not already depend on Serde for other reasons, it may wish to gate Serde impls behind a Cargo cfg. This way downstream libraries only need to pay the cost of compiling Serde if they need those impls to exist. For consistency with other Serde-based libraries, the name of the Cargo cfg should be simply "serde" . Do not use a different name for the cfg like "serde_impls" or "serde_serialization" . The canonical implementation looks like this when not using derive: [dependencies] serde = { version = "1.0", optional = true } #![allow(unused)] fn main() { pub struct T { /* ... */ } #[cfg(feature = "serde")] impl Serialize for T { /* ... */ } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for T { /* ... */ } } And when using derive: [dependencies] serde = { version = "1.0", optional = true, features = ["derive"] } #![allow(unused)] fn main() { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct T { /* ... */ } } Types are Send and Sync where possible (C-SEND-SYNC) Send and Sync are automatically implemented when the compiler determines it is appropriate. In types that manipulate raw pointers, be vigilant that the Send and Sync status of your type accurately reflects its thread safety characteristics. Tests like the following can help catch unintentional regressions in whether the type implements Send or Sync . #![allow(unused)] fn main() { #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<MyStrangeType>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<MyStrangeType>(); } } Error types are meaningful and well-behaved (C-GOOD-ERR) An error type is any type E used in a Result<T, E> returned by any public function of your crate. Error types should always implement the std::error::Error trait which is the mechanism by which error handling libraries like error-chain abstract over different types of errors, and which allows the error to be used as the source() of another error. Additionally, error types should implement the Send and Sync traits. An error that is not Send cannot be returned by a thread run with thread::spawn . An error that is not Sync cannot be passed across threads using an Arc . These are common requirements for basic error handling in a multithreaded application. Send and Sync are also important for being able to package a custom error into an IO error using std::io::Error::new , which requires a trait bound of Error + Send + Sync . One place to be vigilant about this guideline is in functions that return Error trait objects, for example reqwest::Error::get_ref . Typically Error + Send + Sync + 'static will be the most useful for callers. The addition of 'static allows the trait object to be used with Error::downcast_ref . Never use () as an error type, even where there is no useful additional information for the error to carry. () does not implement Error so it cannot be used with error handling libraries like error-chain . () does not implement Display so a user would need to write an error message of their own if they want to fail because of the error. () has an unhelpful Debug representation for users that decide to unwrap() the error. It would not be semantically meaningful for a downstream library to implement From<()> for their error type, so () as an error type cannot be used with the ? operator. Instead, define a meaningful error type specific to your crate or to the individual function. Provide appropriate Error and Display impls. If there is no useful information for the error to carry, it can be implemented as a unit struct. #![allow(unused)] fn main() { use std::error::Error; use std::fmt::Display; // Instead of this... fn do_the_thing() -> Result<Wow, ()> // Prefer this... fn do_the_thing() -> Result<Wow, DoError> #[derive(Debug)] struct DoError; impl Display for DoError { /* ... */ } impl Error for DoError { /* ... */ } } The error message given by the Display representation of an error type should be lowercase without trailing punctuation, and typically concise. Error::description() should not be implemented. It has been deprecated and users should always use Display instead of description() to print the error. Examples from the standard library ParseBoolError is returned when failing to parse a bool from a string. Examples of error messages "unexpected end of file" "provided string was not `true` or `false`" "invalid IP address syntax" "second time provided was later than self" "invalid UTF-8 sequence of {} bytes from index {}" "environment variable was not valid unicode: {:?}" Binary number types provide Hex , Octal , Binary formatting (C-NUM-FMT) std::fmt::UpperHex std::fmt::LowerHex std::fmt::Octal std::fmt::Binary These traits control the representation of a type under the {:X} , {:x} , {:o} , and {:b} format specifiers. Implement these traits for any number type on which you would consider doing bitwise manipulations like | or & . This is especially appropriate for bitflag types. Numeric quantity types like struct Nanoseconds(u64) probably do not need these. Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE) The standard library contains these two impls: #![allow(unused)] fn main() { impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ } impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ } } That means any function that accepts R: Read or W: Write generic parameters by value can be called with a mut reference if necessary. In the documentation of such functions, briefly remind users that a mut reference can be passed. New Rust users often struggle with this. They may have opened a file and want to read multiple pieces of data out of it, but the function to read one piece consumes the reader by value, so they are stuck. The solution would be to leverage one of the above impls and pass &mut f instead of f as the reader parameter. Examples flate2::read::GzDecoder::new flate2::write::GzEncoder::new serde_json::from_reader serde_json::to_writer | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---list | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#examples-from-the-standard-library | Interoperability - Rust API Guidelines About Checklist 1. Naming 2. Interoperability 3. Macros 4. Documentation 5. Predictability 6. Flexibility 7. Type safety 8. Dependability 9. Debuggability 10. Future proofing 11. Necessities External links Light (default) Rust Coal Navy Ayu Rust API Guidelines Interoperability Types eagerly implement common traits (C-COMMON-TRAITS) Rust's trait system does not allow orphans : roughly, every impl must live either in the crate that defines the trait or the implementing type. Consequently, crates that define new types should eagerly implement all applicable, common traits. To see why, consider the following situation: Crate std defines trait Display . Crate url defines type Url , without implementing Display . Crate webapp imports from both std and url , There is no way for webapp to add Display to Url , since it defines neither. (Note: the newtype pattern can provide an efficient, but inconvenient workaround.) The most important common traits to implement from std are: Copy Clone Eq PartialEq Ord PartialOrd Hash Debug Display Default Note that it is common and expected for types to implement both Default and an empty new constructor. new is the constructor convention in Rust, and users expect it to exist, so if it is reasonable for the basic constructor to take no arguments, then it should, even if it is functionally identical to default . Conversions use the standard traits From , AsRef , AsMut (C-CONV-TRAITS) The following conversion traits should be implemented where it makes sense: From TryFrom AsRef AsMut The following conversion traits should never be implemented: Into TryInto These traits have a blanket impl based on From and TryFrom . Implement those instead. Examples from the standard library From<u16> is implemented for u32 because a smaller integer can always be converted to a bigger integer. From<u32> is not implemented for u16 because the conversion may not be possible if the integer is too big. TryFrom<u32> is implemented for u16 and returns an error if the integer is too big to fit in u16 . From<Ipv6Addr> is implemented for IpAddr , which is a type that can represent both v4 and v6 IP addresses. Collections implement FromIterator and Extend (C-COLLECT) FromIterator and Extend enable collections to be used conveniently with the following iterator methods: Iterator::collect Iterator::partition Iterator::unzip FromIterator is for creating a new collection containing items from an iterator, and Extend is for adding items from an iterator onto an existing collection. Examples from the standard library Vec<T> implements both FromIterator<T> and Extend<T> . Data structures implement Serde's Serialize , Deserialize (C-SERDE) Types that play the role of a data structure should implement Serialize and Deserialize . There is a continuum of types between things that are clearly a data structure and things that are clearly not, with gray area in between. LinkedHashMap and IpAddr are data structures. It would be completely reasonable for somebody to want to read in a LinkedHashMap or IpAddr from a JSON file, or send one over IPC to another process. LittleEndian is not a data structure. It is a marker used by the byteorder crate to optimize at compile time for bytes in a particular order, and in fact an instance of LittleEndian can never exist at runtime. So these are clear-cut examples; the #rust or #serde IRC channels can help assess more ambiguous cases if necessary. If a crate does not already depend on Serde for other reasons, it may wish to gate Serde impls behind a Cargo cfg. This way downstream libraries only need to pay the cost of compiling Serde if they need those impls to exist. For consistency with other Serde-based libraries, the name of the Cargo cfg should be simply "serde" . Do not use a different name for the cfg like "serde_impls" or "serde_serialization" . The canonical implementation looks like this when not using derive: [dependencies] serde = { version = "1.0", optional = true } #![allow(unused)] fn main() { pub struct T { /* ... */ } #[cfg(feature = "serde")] impl Serialize for T { /* ... */ } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for T { /* ... */ } } And when using derive: [dependencies] serde = { version = "1.0", optional = true, features = ["derive"] } #![allow(unused)] fn main() { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct T { /* ... */ } } Types are Send and Sync where possible (C-SEND-SYNC) Send and Sync are automatically implemented when the compiler determines it is appropriate. In types that manipulate raw pointers, be vigilant that the Send and Sync status of your type accurately reflects its thread safety characteristics. Tests like the following can help catch unintentional regressions in whether the type implements Send or Sync . #![allow(unused)] fn main() { #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<MyStrangeType>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<MyStrangeType>(); } } Error types are meaningful and well-behaved (C-GOOD-ERR) An error type is any type E used in a Result<T, E> returned by any public function of your crate. Error types should always implement the std::error::Error trait which is the mechanism by which error handling libraries like error-chain abstract over different types of errors, and which allows the error to be used as the source() of another error. Additionally, error types should implement the Send and Sync traits. An error that is not Send cannot be returned by a thread run with thread::spawn . An error that is not Sync cannot be passed across threads using an Arc . These are common requirements for basic error handling in a multithreaded application. Send and Sync are also important for being able to package a custom error into an IO error using std::io::Error::new , which requires a trait bound of Error + Send + Sync . One place to be vigilant about this guideline is in functions that return Error trait objects, for example reqwest::Error::get_ref . Typically Error + Send + Sync + 'static will be the most useful for callers. The addition of 'static allows the trait object to be used with Error::downcast_ref . Never use () as an error type, even where there is no useful additional information for the error to carry. () does not implement Error so it cannot be used with error handling libraries like error-chain . () does not implement Display so a user would need to write an error message of their own if they want to fail because of the error. () has an unhelpful Debug representation for users that decide to unwrap() the error. It would not be semantically meaningful for a downstream library to implement From<()> for their error type, so () as an error type cannot be used with the ? operator. Instead, define a meaningful error type specific to your crate or to the individual function. Provide appropriate Error and Display impls. If there is no useful information for the error to carry, it can be implemented as a unit struct. #![allow(unused)] fn main() { use std::error::Error; use std::fmt::Display; // Instead of this... fn do_the_thing() -> Result<Wow, ()> // Prefer this... fn do_the_thing() -> Result<Wow, DoError> #[derive(Debug)] struct DoError; impl Display for DoError { /* ... */ } impl Error for DoError { /* ... */ } } The error message given by the Display representation of an error type should be lowercase without trailing punctuation, and typically concise. Error::description() should not be implemented. It has been deprecated and users should always use Display instead of description() to print the error. Examples from the standard library ParseBoolError is returned when failing to parse a bool from a string. Examples of error messages "unexpected end of file" "provided string was not `true` or `false`" "invalid IP address syntax" "second time provided was later than self" "invalid UTF-8 sequence of {} bytes from index {}" "environment variable was not valid unicode: {:?}" Binary number types provide Hex , Octal , Binary formatting (C-NUM-FMT) std::fmt::UpperHex std::fmt::LowerHex std::fmt::Octal std::fmt::Binary These traits control the representation of a type under the {:X} , {:x} , {:o} , and {:b} format specifiers. Implement these traits for any number type on which you would consider doing bitwise manipulations like | or & . This is especially appropriate for bitflag types. Numeric quantity types like struct Nanoseconds(u64) probably do not need these. Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE) The standard library contains these two impls: #![allow(unused)] fn main() { impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ } impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ } } That means any function that accepts R: Read or W: Write generic parameters by value can be called with a mut reference if necessary. In the documentation of such functions, briefly remind users that a mut reference can be passed. New Rust users often struggle with this. They may have opened a file and want to read multiple pieces of data out of it, but the function to read one piece consumes the reader by value, so they are stuck. The solution would be to leverage one of the above impls and pass &mut f instead of f as the reader parameter. Examples flate2::read::GzDecoder::new flate2::write::GzEncoder::new serde_json::from_reader serde_json::to_writer | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#examples-from-the-standard-library-2 | Interoperability - Rust API Guidelines About Checklist 1. Naming 2. Interoperability 3. Macros 4. Documentation 5. Predictability 6. Flexibility 7. Type safety 8. Dependability 9. Debuggability 10. Future proofing 11. Necessities External links Light (default) Rust Coal Navy Ayu Rust API Guidelines Interoperability Types eagerly implement common traits (C-COMMON-TRAITS) Rust's trait system does not allow orphans : roughly, every impl must live either in the crate that defines the trait or the implementing type. Consequently, crates that define new types should eagerly implement all applicable, common traits. To see why, consider the following situation: Crate std defines trait Display . Crate url defines type Url , without implementing Display . Crate webapp imports from both std and url , There is no way for webapp to add Display to Url , since it defines neither. (Note: the newtype pattern can provide an efficient, but inconvenient workaround.) The most important common traits to implement from std are: Copy Clone Eq PartialEq Ord PartialOrd Hash Debug Display Default Note that it is common and expected for types to implement both Default and an empty new constructor. new is the constructor convention in Rust, and users expect it to exist, so if it is reasonable for the basic constructor to take no arguments, then it should, even if it is functionally identical to default . Conversions use the standard traits From , AsRef , AsMut (C-CONV-TRAITS) The following conversion traits should be implemented where it makes sense: From TryFrom AsRef AsMut The following conversion traits should never be implemented: Into TryInto These traits have a blanket impl based on From and TryFrom . Implement those instead. Examples from the standard library From<u16> is implemented for u32 because a smaller integer can always be converted to a bigger integer. From<u32> is not implemented for u16 because the conversion may not be possible if the integer is too big. TryFrom<u32> is implemented for u16 and returns an error if the integer is too big to fit in u16 . From<Ipv6Addr> is implemented for IpAddr , which is a type that can represent both v4 and v6 IP addresses. Collections implement FromIterator and Extend (C-COLLECT) FromIterator and Extend enable collections to be used conveniently with the following iterator methods: Iterator::collect Iterator::partition Iterator::unzip FromIterator is for creating a new collection containing items from an iterator, and Extend is for adding items from an iterator onto an existing collection. Examples from the standard library Vec<T> implements both FromIterator<T> and Extend<T> . Data structures implement Serde's Serialize , Deserialize (C-SERDE) Types that play the role of a data structure should implement Serialize and Deserialize . There is a continuum of types between things that are clearly a data structure and things that are clearly not, with gray area in between. LinkedHashMap and IpAddr are data structures. It would be completely reasonable for somebody to want to read in a LinkedHashMap or IpAddr from a JSON file, or send one over IPC to another process. LittleEndian is not a data structure. It is a marker used by the byteorder crate to optimize at compile time for bytes in a particular order, and in fact an instance of LittleEndian can never exist at runtime. So these are clear-cut examples; the #rust or #serde IRC channels can help assess more ambiguous cases if necessary. If a crate does not already depend on Serde for other reasons, it may wish to gate Serde impls behind a Cargo cfg. This way downstream libraries only need to pay the cost of compiling Serde if they need those impls to exist. For consistency with other Serde-based libraries, the name of the Cargo cfg should be simply "serde" . Do not use a different name for the cfg like "serde_impls" or "serde_serialization" . The canonical implementation looks like this when not using derive: [dependencies] serde = { version = "1.0", optional = true } #![allow(unused)] fn main() { pub struct T { /* ... */ } #[cfg(feature = "serde")] impl Serialize for T { /* ... */ } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for T { /* ... */ } } And when using derive: [dependencies] serde = { version = "1.0", optional = true, features = ["derive"] } #![allow(unused)] fn main() { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct T { /* ... */ } } Types are Send and Sync where possible (C-SEND-SYNC) Send and Sync are automatically implemented when the compiler determines it is appropriate. In types that manipulate raw pointers, be vigilant that the Send and Sync status of your type accurately reflects its thread safety characteristics. Tests like the following can help catch unintentional regressions in whether the type implements Send or Sync . #![allow(unused)] fn main() { #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<MyStrangeType>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<MyStrangeType>(); } } Error types are meaningful and well-behaved (C-GOOD-ERR) An error type is any type E used in a Result<T, E> returned by any public function of your crate. Error types should always implement the std::error::Error trait which is the mechanism by which error handling libraries like error-chain abstract over different types of errors, and which allows the error to be used as the source() of another error. Additionally, error types should implement the Send and Sync traits. An error that is not Send cannot be returned by a thread run with thread::spawn . An error that is not Sync cannot be passed across threads using an Arc . These are common requirements for basic error handling in a multithreaded application. Send and Sync are also important for being able to package a custom error into an IO error using std::io::Error::new , which requires a trait bound of Error + Send + Sync . One place to be vigilant about this guideline is in functions that return Error trait objects, for example reqwest::Error::get_ref . Typically Error + Send + Sync + 'static will be the most useful for callers. The addition of 'static allows the trait object to be used with Error::downcast_ref . Never use () as an error type, even where there is no useful additional information for the error to carry. () does not implement Error so it cannot be used with error handling libraries like error-chain . () does not implement Display so a user would need to write an error message of their own if they want to fail because of the error. () has an unhelpful Debug representation for users that decide to unwrap() the error. It would not be semantically meaningful for a downstream library to implement From<()> for their error type, so () as an error type cannot be used with the ? operator. Instead, define a meaningful error type specific to your crate or to the individual function. Provide appropriate Error and Display impls. If there is no useful information for the error to carry, it can be implemented as a unit struct. #![allow(unused)] fn main() { use std::error::Error; use std::fmt::Display; // Instead of this... fn do_the_thing() -> Result<Wow, ()> // Prefer this... fn do_the_thing() -> Result<Wow, DoError> #[derive(Debug)] struct DoError; impl Display for DoError { /* ... */ } impl Error for DoError { /* ... */ } } The error message given by the Display representation of an error type should be lowercase without trailing punctuation, and typically concise. Error::description() should not be implemented. It has been deprecated and users should always use Display instead of description() to print the error. Examples from the standard library ParseBoolError is returned when failing to parse a bool from a string. Examples of error messages "unexpected end of file" "provided string was not `true` or `false`" "invalid IP address syntax" "second time provided was later than self" "invalid UTF-8 sequence of {} bytes from index {}" "environment variable was not valid unicode: {:?}" Binary number types provide Hex , Octal , Binary formatting (C-NUM-FMT) std::fmt::UpperHex std::fmt::LowerHex std::fmt::Octal std::fmt::Binary These traits control the representation of a type under the {:X} , {:x} , {:o} , and {:b} format specifiers. Implement these traits for any number type on which you would consider doing bitwise manipulations like | or & . This is especially appropriate for bitflag types. Numeric quantity types like struct Nanoseconds(u64) probably do not need these. Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE) The standard library contains these two impls: #![allow(unused)] fn main() { impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ } impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ } } That means any function that accepts R: Read or W: Write generic parameters by value can be called with a mut reference if necessary. In the documentation of such functions, briefly remind users that a mut reference can be passed. New Rust users often struggle with this. They may have opened a file and want to read multiple pieces of data out of it, but the function to read one piece consumes the reader by value, so they are stuck. The solution would be to leverage one of the above impls and pass &mut f instead of f as the reader parameter. Examples flate2::read::GzDecoder::new flate2::write::GzEncoder::new serde_json::from_reader serde_json::to_writer | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-metadata.html | cargo metadata - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-metadata(1) NAME cargo-metadata — Machine-readable metadata about the current package SYNOPSIS cargo metadata [ options ] DESCRIPTION Output JSON to stdout containing information about the workspace members and resolved dependencies of the current package. The output format is subject to change in future versions of Cargo. It is recommended to include the --format-version flag to future-proof your code and ensure the output is in the format you are expecting. For more on the expectations, see “Compatibility” . See the cargo_metadata crate for a Rust API for reading the metadata. OUTPUT FORMAT Compatibility Within the same output format version, the compatibility is maintained, except some scenarios. The following is a non-exhaustive list of changes that are not considered as incompatible: Adding new fields — New fields will be added when needed. Reserving this helps Cargo evolve without bumping the format version too often. Adding new values for enum-like fields — Same as adding new fields. It keeps metadata evolving without stagnation. Changing opaque representations — The inner representations of some fields are implementation details. For example, fields related to “Source ID” are treated as opaque identifiers to differentiate packages or sources. Consumers shouldn’t rely on those representations unless specified. JSON format The JSON output has the following format: { /* Array of all packages in the workspace. It also includes all feature-enabled dependencies unless --no-deps is used. */ "packages": [ { /* The name of the package. */ "name": "my-package", /* The version of the package. */ "version": "0.1.0", /* The Package ID for referring to the package within the document and as the `--package` argument to many commands */ "id": "file:///path/to/my-package#0.1.0", /* The license value from the manifest, or null. */ "license": "MIT/Apache-2.0", /* The license-file value from the manifest, or null. */ "license_file": "LICENSE", /* The description value from the manifest, or null. */ "description": "Package description.", /* The source ID of the package, an "opaque" identifier representing where a package is retrieved from. See "Compatibility" above for the stability guarantee. This is null for path dependencies and workspace members. For other dependencies, it is a string with the format: - "registry+URL" for registry-based dependencies. Example: "registry+https://github.com/rust-lang/crates.io-index" - "git+URL" for git-based dependencies. Example: "git+https://github.com/rust-lang/cargo?rev=5e85ba14aaa20f8133863373404cb0af69eeef2c#5e85ba14aaa20f8133863373404cb0af69eeef2c" - "sparse+URL" for dependencies from a sparse registry Example: "sparse+https://my-sparse-registry.org" The value after the `+` is not explicitly defined, and may change between versions of Cargo and may not directly correlate to other things, such as registry definitions in a config file. New source kinds may be added in the future which will have different `+` prefixed identifiers. */ "source": null, /* Array of dependencies declared in the package's manifest. */ "dependencies": [ { /* The name of the dependency. */ "name": "bitflags", /* The source ID of the dependency. May be null, see description for the package source. */ "source": "registry+https://github.com/rust-lang/crates.io-index", /* The version requirement for the dependency. Dependencies without a version requirement have a value of "*". */ "req": "^1.0", /* The dependency kind. "dev", "build", or null for a normal dependency. */ "kind": null, /* If the dependency is renamed, this is the new name for the dependency as a string. null if it is not renamed. */ "rename": null, /* Boolean of whether or not this is an optional dependency. */ "optional": false, /* Boolean of whether or not default features are enabled. */ "uses_default_features": true, /* Array of features enabled. */ "features": [], /* The target platform for the dependency. null if not a target dependency. */ "target": "cfg(windows)", /* The file system path for a local path dependency. not present if not a path dependency. */ "path": "/path/to/dep", /* A string of the URL of the registry this dependency is from. If not specified or null, the dependency is from the default registry (crates.io). */ "registry": null, /* (unstable) Boolean flag of whether or not this is a pulbic dependency. This field is only present when `-Zpublic-dependency` is enabled. */ "public": false } ], /* Array of Cargo targets. */ "targets": [ { /* Array of target kinds. - lib targets list the `crate-type` values from the manifest such as "lib", "rlib", "dylib", "proc-macro", etc. (default ["lib"]) - binary is ["bin"] - example is ["example"] - integration test is ["test"] - benchmark is ["bench"] - build script is ["custom-build"] */ "kind": [ "bin" ], /* Array of crate types. - lib and example libraries list the `crate-type` values from the manifest such as "lib", "rlib", "dylib", "proc-macro", etc. (default ["lib"]) - all other target kinds are ["bin"] */ "crate_types": [ "bin" ], /* The name of the target. For lib targets, dashes will be replaced with underscores. */ "name": "my-package", /* Absolute path to the root source file of the target. */ "src_path": "/path/to/my-package/src/main.rs", /* The Rust edition of the target. Defaults to the package edition. */ "edition": "2018", /* Array of required features. This property is not included if no required features are set. */ "required-features": ["feat1"], /* Whether the target should be documented by `cargo doc`. */ "doc": true, /* Whether or not this target has doc tests enabled, and the target is compatible with doc testing. */ "doctest": false, /* Whether or not this target should be built and run with `--test` */ "test": true } ], /* Set of features defined for the package. Each feature maps to an array of features or dependencies it enables. */ "features": { "default": [ "feat1" ], "feat1": [], "feat2": [] }, /* Absolute path to this package's manifest. */ "manifest_path": "/path/to/my-package/Cargo.toml", /* Package metadata. This is null if no metadata is specified. */ "metadata": { "docs": { "rs": { "all-features": true } } }, /* List of registries to which this package may be published. Publishing is unrestricted if null, and forbidden if an empty array. */ "publish": [ "crates-io" ], /* Array of authors from the manifest. Empty array if no authors specified. */ "authors": [ "Jane Doe <user@example.com>" ], /* Array of categories from the manifest. */ "categories": [ "command-line-utilities" ], /* Optional string that is the default binary picked by cargo run. */ "default_run": null, /* Optional string that is the minimum supported rust version */ "rust_version": "1.56", /* Array of keywords from the manifest. */ "keywords": [ "cli" ], /* The readme value from the manifest or null if not specified. */ "readme": "README.md", /* The repository value from the manifest or null if not specified. */ "repository": "https://github.com/rust-lang/cargo", /* The homepage value from the manifest or null if not specified. */ "homepage": "https://rust-lang.org", /* The documentation value from the manifest or null if not specified. */ "documentation": "https://doc.rust-lang.org/stable/std", /* The default edition of the package. Note that individual targets may have different editions. */ "edition": "2018", /* Optional string that is the name of a native library the package is linking to. */ "links": null, } ], /* Array of members of the workspace. Each entry is the Package ID for the package. */ "workspace_members": [ "file:///path/to/my-package#0.1.0", ], /* Array of default members of the workspace. Each entry is the Package ID for the package. */ "workspace_default_members": [ "file:///path/to/my-package#0.1.0", ], // The resolved dependency graph for the entire workspace. The enabled // features are based on the enabled features for the "current" package. // Inactivated optional dependencies are not listed. // // This is null if --no-deps is specified. // // By default, this includes all dependencies for all target platforms. // The `--filter-platform` flag may be used to narrow to a specific // target triple. "resolve": { /* Array of nodes within the dependency graph. Each node is a package. */ "nodes": [ { /* The Package ID of this node. */ "id": "file:///path/to/my-package#0.1.0", /* The dependencies of this package, an array of Package IDs. */ "dependencies": [ "https://github.com/rust-lang/crates.io-index#bitflags@1.0.4" ], /* The dependencies of this package. This is an alternative to "dependencies" which contains additional information. In particular, this handles renamed dependencies. */ "deps": [ { /* The name of the dependency's library target. If this is a renamed dependency, this is the new name. */ "name": "bitflags", /* The Package ID of the dependency. */ "pkg": "https://github.com/rust-lang/crates.io-index#bitflags@1.0.4" /* Array of dependency kinds. Added in Cargo 1.40. */ "dep_kinds": [ { /* The dependency kind. "dev", "build", or null for a normal dependency. */ "kind": null, /* The target platform for the dependency. null if not a target dependency. */ "target": "cfg(windows)" } ] } ], /* Array of features enabled on this package. */ "features": [ "default" ] } ], /* The package in the current working directory (if --manifest-path is not given). This is null if there is a virtual workspace. Otherwise it is the Package ID of the package. */ "root": "file:///path/to/my-package#0.1.0", }, /* The absolute path to the target directory where Cargo places its output. */ "target_directory": "/path/to/my-package/target", /* The absolute path to the build directory where Cargo places intermediate build artifacts. (unstable) */ "build_directory": "/path/to/my-package/build-dir", /* The version of the schema for this metadata structure. This will be changed if incompatible changes are ever made. */ "version": 1, /* The absolute path to the root of the workspace. */ "workspace_root": "/path/to/my-package" /* Workspace metadata. This is null if no metadata is specified. */ "metadata": { "docs": { "rs": { "all-features": true } } } } Notes: For "id" field syntax, see Package ID Specifications in the reference. OPTIONS Output Options --no-deps Output information only about the workspace members and don’t fetch dependencies. --format-version version Specify the version of the output format to use. Currently 1 is the only possible value. --filter-platform triple This filters the resolve output to only include dependencies for the given target triple . Without this flag, the resolve includes all targets. Note that the dependencies listed in the “packages” array still includes all dependencies. Each package definition is intended to be an unaltered reproduction of the information within Cargo.toml . Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Output JSON about the current package: cargo metadata --format-version=1 SEE ALSO cargo(1) , cargo-pkgid(1) , Package ID Specifications , JSON messages | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#cargo_vcs_infojson-format | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/reference/config.html#build | Configuration - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book Configuration This document explains how Cargo’s configuration system works, as well as available keys or configuration. For configuration of a package through its manifest, see the manifest format . Hierarchical structure Cargo allows local configuration for a particular package as well as global configuration. It looks for configuration files in the current directory and all parent directories. If, for example, Cargo were invoked in /projects/foo/bar/baz , then the following configuration files would be probed for and unified in this order: /projects/foo/bar/baz/.cargo/config.toml /projects/foo/bar/.cargo/config.toml /projects/foo/.cargo/config.toml /projects/.cargo/config.toml /.cargo/config.toml $CARGO_HOME/config.toml which defaults to: Windows: %USERPROFILE%\.cargo\config.toml Unix: $HOME/.cargo/config.toml With this structure, you can specify configuration per-package, and even possibly check it into version control. You can also specify personal defaults with a configuration file in your home directory. If a key is specified in multiple config files, the values will get merged together. Numbers, strings, and booleans will use the value in the deeper config directory taking precedence over ancestor directories, where the home directory is the lowest priority. Arrays will be joined together with higher precedence items being placed later in the merged array. At present, when being invoked from a workspace, Cargo does not read config files from crates within the workspace. i.e. if a workspace has two crates in it, named /projects/foo/bar/baz/mylib and /projects/foo/bar/baz/mybin , and there are Cargo configs at /projects/foo/bar/baz/mylib/.cargo/config.toml and /projects/foo/bar/baz/mybin/.cargo/config.toml , Cargo does not read those configuration files if it is invoked from the workspace root ( /projects/foo/bar/baz/ ). Note: Cargo also reads config files without the .toml extension, such as .cargo/config . Support for the .toml extension was added in version 1.39 and is the preferred form. If both files exist, Cargo will use the file without the extension. Configuration format Configuration files are written in the TOML format (like the manifest), with simple key-value pairs inside of sections (tables). The following is a quick overview of all settings, with detailed descriptions found below. paths = ["/path/to/override"] # path dependency overrides [alias] # command aliases b = "build" c = "check" t = "test" r = "run" rr = "run --release" recursive_example = "rr --example recursions" space_example = ["run", "--release", "--", "\"command list\""] [build] jobs = 1 # number of parallel jobs, defaults to # of CPUs rustc = "rustc" # the rust compiler tool rustc-wrapper = "…" # run this wrapper instead of `rustc` rustc-workspace-wrapper = "…" # run this wrapper instead of `rustc` for workspace members rustdoc = "rustdoc" # the doc generator tool target = "triple" # build for the target triple (ignored by `cargo install`) target-dir = "target" # path of where to place generated artifacts build-dir = "target" # path of where to place intermediate build artifacts rustflags = ["…", "…"] # custom flags to pass to all compiler invocations rustdocflags = ["…", "…"] # custom flags to pass to rustdoc incremental = true # whether or not to enable incremental compilation dep-info-basedir = "…" # path for the base directory for targets in depfiles [credential-alias] # Provides a way to define aliases for credential providers. my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] [doc] browser = "chromium" # browser to use with `cargo doc --open`, # overrides the `BROWSER` environment variable [env] # Set ENV_VAR_NAME=value for any process run by Cargo ENV_VAR_NAME = "value" # Set even if already present in environment ENV_VAR_NAME_2 = { value = "value", force = true } # `value` is relative to the parent of `.cargo/config.toml`, env var will be the full absolute path ENV_VAR_NAME_3 = { value = "relative/path", relative = true } [future-incompat-report] frequency = 'always' # when to display a notification about a future incompat report [cache] auto-clean-frequency = "1 day" # How often to perform automatic cache cleaning [cargo-new] vcs = "none" # VCS to use ('git', 'hg', 'pijul', 'fossil', 'none') [http] debug = false # HTTP debugging proxy = "host:port" # HTTP proxy in libcurl format ssl-version = "tlsv1.3" # TLS version to use ssl-version.max = "tlsv1.3" # maximum TLS version ssl-version.min = "tlsv1.1" # minimum TLS version timeout = 30 # timeout for each HTTP request, in seconds low-speed-limit = 10 # network timeout threshold (bytes/sec) cainfo = "cert.pem" # path to Certificate Authority (CA) bundle proxy-cainfo = "cert.pem" # path to proxy Certificate Authority (CA) bundle check-revoke = true # check for SSL certificate revocation multiplexing = true # HTTP/2 multiplexing user-agent = "…" # the user-agent header [install] root = "/some/path" # `cargo install` destination directory [net] retry = 3 # network retries git-fetch-with-cli = true # use the `git` executable for git operations offline = true # do not access the network [net.ssh] known-hosts = ["..."] # known SSH host keys [patch.<registry>] # Same keys as for [patch] in Cargo.toml [profile.<name>] # Modify profile settings via config. inherits = "dev" # Inherits settings from [profile.dev]. opt-level = 0 # Optimization level. debug = true # Include debug info. split-debuginfo = '...' # Debug info splitting behavior. strip = "none" # Removes symbols or debuginfo. debug-assertions = true # Enables debug assertions. overflow-checks = true # Enables runtime integer overflow checks. lto = false # Sets link-time optimization. panic = 'unwind' # The panic strategy. incremental = true # Incremental compilation. codegen-units = 16 # Number of code generation units. rpath = false # Sets the rpath linking option. [profile.<name>.build-override] # Overrides build-script settings. # Same keys for a normal profile. [profile.<name>.package.<name>] # Override profile for a package. # Same keys for a normal profile (minus `panic`, `lto`, and `rpath`). [resolver] incompatible-rust-versions = "allow" # Specifies how resolver reacts to these [registries.<name>] # registries other than crates.io index = "…" # URL of the registry index token = "…" # authentication token for the registry credential-provider = "cargo:token" # The credential provider for this registry. [registries.crates-io] protocol = "sparse" # The protocol to use to access crates.io. [registry] default = "…" # name of the default registry token = "…" # authentication token for crates.io credential-provider = "cargo:token" # The credential provider for crates.io. global-credential-providers = ["cargo:token"] # The credential providers to use by default. [source.<name>] # source definition and replacement replace-with = "…" # replace this source with the given named source directory = "…" # path to a directory source registry = "…" # URL to a registry source local-registry = "…" # path to a local registry source git = "…" # URL of a git repository source branch = "…" # branch name for the git repository tag = "…" # tag name for the git repository rev = "…" # revision for the git repository [target.<triple>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` rustdocflags = ["…", "…"] # custom flags for `rustdoc` [target.<cfg>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` [target.<triple>.<links>] # `links` build script override rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] quiet = false # whether cargo output is quiet verbose = false # whether cargo provides verbose output color = 'auto' # whether cargo colorizes output hyperlinks = true # whether cargo inserts links into output unicode = true # whether cargo can render output using non-ASCII unicode characters progress.when = 'auto' # whether cargo shows progress bar progress.width = 80 # width of progress bar progress.term-integration = true # whether cargo reports progress to terminal emulator Environment variables Cargo can also be configured through environment variables in addition to the TOML configuration files. For each configuration key of the form foo.bar the environment variable CARGO_FOO_BAR can also be used to define the value. Keys are converted to uppercase, dots and dashes are converted to underscores. For example the target.x86_64-unknown-linux-gnu.runner key can also be defined by the CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER environment variable. Environment variables will take precedence over TOML configuration files. Currently only integer, boolean, string and some array values are supported to be defined by environment variables. Descriptions below indicate which keys support environment variables and otherwise they are not supported due to technical issues . In addition to the system above, Cargo recognizes a few other specific environment variables . Command-line overrides Cargo also accepts arbitrary configuration overrides through the --config command-line option. The argument should be in TOML syntax of KEY=VALUE or provided as a path to an extra configuration file: # With `KEY=VALUE` in TOML syntax cargo --config net.git-fetch-with-cli=true fetch # With a path to a configuration file cargo --config ./path/to/my/extra-config.toml fetch The --config option may be specified multiple times, in which case the values are merged in left-to-right order, using the same merging logic that is used when multiple configuration files apply. Configuration values specified this way take precedence over environment variables, which take precedence over configuration files. When the --config option is provided as an extra configuration file, The configuration file loaded this way follow the same precedence rules as other options specified directly with --config . Some examples of what it looks like using Bourne shell syntax: # Most shells will require escaping. cargo --config http.proxy=\"http://example.com\" … # Spaces may be used. cargo --config "net.git-fetch-with-cli = true" … # TOML array example. Single quotes make it easier to read and write. cargo --config 'build.rustdocflags = ["--html-in-header", "header.html"]' … # Example of a complex TOML key. cargo --config "target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))'.runner = 'my-runner'" … # Example of overriding a profile setting. cargo --config profile.dev.package.image.opt-level=3 … Config-relative paths Paths in config files may be absolute, relative, or a bare name without any path separators. Paths for executables without a path separator will use the PATH environment variable to search for the executable. Paths for non-executables will be relative to where the config value is defined. In particular, rules are: For environment variables, paths are relative to the current working directory. For config values loaded directly from the --config KEY=VALUE option, paths are relative to the current working directory. For config files, paths are relative to the parent directory of the directory where the config files were defined, no matter those files are from either the hierarchical probing or the --config <path> option. Note: To maintain consistency with existing .cargo/config.toml probing behavior, it is by design that a path in a config file passed via --config <path> is also relative to two levels up from the config file itself. To avoid unexpected results, the rule of thumb is putting your extra config files at the same level of discovered .cargo/config.toml in your project. For instance, given a project /my/project , it is recommended to put config files under /my/project/.cargo or a new directory at the same level, such as /my/project/.config . # Relative path examples. [target.x86_64-unknown-linux-gnu] runner = "foo" # Searches `PATH` for `foo`. [source.vendored-sources] # Directory is relative to the parent where `.cargo/config.toml` is located. # For example, `/my/project/.cargo/config.toml` would result in `/my/project/vendor`. directory = "vendor" Executable paths with arguments Some Cargo commands invoke external programs, which can be configured as a path and some number of arguments. The value may be an array of strings like ['/path/to/program', 'somearg'] or a space-separated string like '/path/to/program somearg' . If the path to the executable contains a space, the list form must be used. If Cargo is passing other arguments to the program such as a path to open or run, they will be passed after the last specified argument in the value of an option of this format. If the specified program does not have path separators, Cargo will search PATH for its executable. Credentials Configuration values with sensitive information are stored in the $CARGO_HOME/credentials.toml file. This file is automatically created and updated by cargo login and cargo logout when using the cargo:token credential provider. Tokens are used by some Cargo commands such as cargo publish for authenticating with remote registries. Care should be taken to protect the tokens and to keep them secret. It follows the same format as Cargo config files. [registry] token = "…" # Access token for crates.io [registries.<name>] token = "…" # Access token for the named registry As with most other config values, tokens may be specified with environment variables. The token for crates.io may be specified with the CARGO_REGISTRY_TOKEN environment variable. Tokens for other registries may be specified with environment variables of the form CARGO_REGISTRIES_<name>_TOKEN where <name> is the name of the registry in all capital letters. Note: Cargo also reads and writes credential files without the .toml extension, such as .cargo/credentials . Support for the .toml extension was added in version 1.39. In version 1.68, Cargo writes to the file with the extension by default. However, for backward compatibility reason, when both files exist, Cargo will read and write the file without the extension. Configuration keys This section documents all configuration keys. The description for keys with variable parts are annotated with angled brackets like target.<triple> where the <triple> part can be any target triple like target.x86_64-pc-windows-msvc . paths Type: array of strings (paths) Default: none Environment: not supported An array of paths to local packages which are to be used as overrides for dependencies. For more information see the Overriding Dependencies guide . [alias] Type: string or array of strings Default: see below Environment: CARGO_ALIAS_<name> The [alias] table defines CLI command aliases. For example, running cargo b is an alias for running cargo build . Each key in the table is the subcommand, and the value is the actual command to run. The value may be an array of strings, where the first element is the command and the following are arguments. It may also be a string, which will be split on spaces into subcommand and arguments. The following aliases are built-in to Cargo: [alias] b = "build" c = "check" d = "doc" t = "test" r = "run" rm = "remove" Aliases are not allowed to redefine existing built-in commands. Aliases are recursive: [alias] rr = "run --release" recursive_example = "rr --example recursions" [build] The [build] table controls build-time operations and compiler settings. build.jobs Type: integer or string Default: number of logical CPUs Environment: CARGO_BUILD_JOBS Sets the maximum number of compiler processes to run in parallel. If negative, it sets the maximum number of compiler processes to the number of logical CPUs plus provided value. Should not be 0. If a string default is provided, it sets the value back to defaults. Can be overridden with the --jobs CLI option. build.rustc Type: string (program path) Default: "rustc" Environment: CARGO_BUILD_RUSTC or RUSTC Sets the executable to use for rustc . build.rustc-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WRAPPER or RUSTC_WRAPPER Sets a wrapper to execute instead of rustc . The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). build.rustc-workspace-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER or RUSTC_WORKSPACE_WRAPPER Sets a wrapper to execute instead of rustc , for workspace members only. When building a single-package project without workspaces, that package is considered to be the workspace. The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). It affects the filename hash so that artifacts produced by the wrapper are cached separately. If both rustc-wrapper and rustc-workspace-wrapper are set, then they will be nested: the final invocation is $RUSTC_WRAPPER $RUSTC_WORKSPACE_WRAPPER $RUSTC . build.rustdoc Type: string (program path) Default: "rustdoc" Environment: CARGO_BUILD_RUSTDOC or RUSTDOC Sets the executable to use for rustdoc . build.target Type: string or array of strings Default: host platform Environment: CARGO_BUILD_TARGET The default target platform triples to compile to. Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. Can be overridden with the --target CLI option. [build] target = ["x86_64-unknown-linux-gnu", "i686-unknown-linux-gnu"] build.target-dir Type: string (path) Default: "target" Environment: CARGO_BUILD_TARGET_DIR or CARGO_TARGET_DIR The path to where all compiler output is placed. The default if not specified is a directory named target located at the root of the workspace. Can be overridden with the --target-dir CLI option. For more information see the build cache documentation . build.build-dir Type: string (path) Default: Defaults to the value of build.target-dir Environment: CARGO_BUILD_BUILD_DIR The directory where intermediate build artifacts will be stored. Intermediate artifacts are produced by Rustc/Cargo during the build process. This option supports path templating. Available template variables: {workspace-root} resolves to root of the current workspace. {cargo-cache-home} resolves to CARGO_HOME {workspace-path-hash} resolves to a hash of the manifest path For more information see the build cache documentation . build.rustflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS or RUSTFLAGS Extra command-line flags to pass to rustc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTFLAGS environment variable. RUSTFLAGS environment variable. All matching target.<triple>.rustflags and target.<cfg>.rustflags config entries joined together. build.rustflags config value. Additional flags may also be passed with the cargo rustc command. If the --target flag (or build.target ) is used, then the flags will only be passed to the compiler for the target. Things being built for the host, such as build scripts or proc macros, will not receive the args. Without --target , the flags will be passed to all compiler invocations (including build scripts and proc macros) because dependencies are shared. If you have args that you do not want to pass to build scripts or proc macros and are building for the host, pass --target with the host triple . It is not recommended to pass in flags that Cargo itself usually manages. For example, the flags driven by profiles are best handled by setting the appropriate profile setting. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.rustdocflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTDOCFLAGS or CARGO_ENCODED_RUSTDOCFLAGS or RUSTDOCFLAGS Extra command-line flags to pass to rustdoc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTDOCFLAGS environment variable. RUSTDOCFLAGS environment variable. All matching target.<triple>.rustdocflags config entries joined together. build.rustdocflags config value. Additional flags may also be passed with the cargo rustdoc command. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.incremental Type: bool Default: from profile Environment: CARGO_BUILD_INCREMENTAL or CARGO_INCREMENTAL Whether or not to perform incremental compilation . The default if not set is to use the value from the profile . Otherwise this overrides the setting of all profiles. The CARGO_INCREMENTAL environment variable can be set to 1 to force enable incremental compilation for all profiles, or 0 to disable it. This env var overrides the config setting. build.dep-info-basedir Type: string (path) Default: none Environment: CARGO_BUILD_DEP_INFO_BASEDIR Strips the given path prefix from dep info file paths. This config setting is intended to convert absolute paths to relative paths for tools that require relative paths. The setting itself is a config-relative path. So, for example, a value of "." would strip all paths starting with the parent directory of the .cargo directory. build.pipelining This option is deprecated and unused. Cargo always has pipelining enabled. [credential-alias] Type: string or array of strings Default: empty Environment: CARGO_CREDENTIAL_ALIAS_<name> The [credential-alias] table defines credential provider aliases. These aliases can be referenced as an element of the registry.global-credential-providers array, or as a credential provider for a specific registry under registries.<NAME>.credential-provider . If specified as a string, the value will be split on spaces into path and arguments. For example, to define an alias called my-alias : [credential-alias] my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] See Registry Authentication for more information. [doc] The [doc] table defines options for the cargo doc command. doc.browser Type: string or array of strings ( program path with args ) Default: BROWSER environment variable, or, if that is missing, opening the link in a system specific way This option sets the browser to be used by cargo doc , overriding the BROWSER environment variable when opening documentation with the --open option. [cargo-new] The [cargo-new] table defines defaults for the cargo new command. cargo-new.name This option is deprecated and unused. cargo-new.email This option is deprecated and unused. cargo-new.vcs Type: string Default: "git" or "none" Environment: CARGO_CARGO_NEW_VCS Specifies the source control system to use for initializing a new repository. Valid values are git , hg (for Mercurial), pijul , fossil or none to disable this behavior. Defaults to git , or none if already inside a VCS repository. Can be overridden with the --vcs CLI option. [env] The [env] section allows you to set additional environment variables for build scripts, rustc invocations, cargo run and cargo build . [env] OPENSSL_DIR = "/opt/openssl" By default, the variables specified will not override values that already exist in the environment. This behavior can be changed by setting the force flag. Setting the relative flag evaluates the value as a config-relative path that is relative to the parent directory of the .cargo directory that contains the config.toml file. The value of the environment variable will be the full absolute path. [env] TMPDIR = { value = "/home/tmp", force = true } OPENSSL_DIR = { value = "vendor/openssl", relative = true } [future-incompat-report] The [future-incompat-report] table controls setting for future incompat reporting future-incompat-report.frequency Type: string Default: "always" Environment: CARGO_FUTURE_INCOMPAT_REPORT_FREQUENCY Controls how often we display a notification to the terminal when a future incompat report is available. Possible values: always (default): Always display a notification when a command (e.g. cargo build ) produces a future incompat report never : Never display a notification [cache] The [cache] table defines settings for cargo’s caches. Global caches When running cargo commands, Cargo will automatically track which files you are using within the global cache. Periodically, Cargo will delete files that have not been used for some period of time. It will delete files that have to be downloaded from the network if they have not been used in 3 months. Files that can be generated without network access will be deleted if they have not been used in 1 month. The automatic deletion of files only occurs when running commands that are already doing a significant amount of work, such as all of the build commands ( cargo build , cargo test , cargo check , etc.), and cargo fetch . Automatic deletion is disabled if cargo is offline such as with --offline or --frozen to avoid deleting artifacts that may need to be used if you are offline for a long period of time. Note : This tracking is currently only implemented for the global cache in Cargo’s home directory. This includes registry indexes and source files downloaded from registries and git dependencies. Support for tracking build artifacts is not yet implemented, and tracked in cargo#13136 . Additionally, there is an unstable feature to support manually triggering cache cleaning, and to further customize the configuration options. See the Unstable chapter for more information. cache.auto-clean-frequency Type: string Default: "1 day" Environment: CARGO_CACHE_AUTO_CLEAN_FREQUENCY This option defines how often Cargo will automatically delete unused files in the global cache. This does not define how old the files must be, those thresholds are described above . It supports the following settings: "never" — Never deletes old files. "always" — Checks to delete old files every time Cargo runs. An integer followed by “seconds”, “minutes”, “hours”, “days”, “weeks”, or “months” — Checks to delete old files at most the given time frame. [http] The [http] table defines settings for HTTP behavior. This includes fetching crate dependencies and accessing remote git repositories. http.debug Type: boolean Default: false Environment: CARGO_HTTP_DEBUG If true , enables debugging of HTTP requests. The debug information can be seen by setting the CARGO_LOG=network=debug environment variable (or use network=trace for even more information). Be wary when posting logs from this output in a public location. The output may include headers with authentication tokens which you don’t want to leak! Be sure to review logs before posting them. http.proxy Type: string Default: none Environment: CARGO_HTTP_PROXY or HTTPS_PROXY or https_proxy or http_proxy Sets an HTTP and HTTPS proxy to use. The format is in libcurl format as in [protocol://]host[:port] . If not set, Cargo will also check the http.proxy setting in your global git configuration. If none of those are set, the HTTPS_PROXY or https_proxy environment variables set the proxy for HTTPS requests, and http_proxy sets it for HTTP requests. http.timeout Type: integer Default: 30 Environment: CARGO_HTTP_TIMEOUT or HTTP_TIMEOUT Sets the timeout for each HTTP request, in seconds. http.cainfo Type: string (path) Default: none Environment: CARGO_HTTP_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify TLS certificates. If not specified, Cargo attempts to use the system certificates. http.proxy-cainfo Type: string (path) Default: falls back to http.cainfo if not set Environment: CARGO_HTTP_PROXY_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify proxy TLS certificates. http.check-revoke Type: boolean Default: true (Windows) false (all others) Environment: CARGO_HTTP_CHECK_REVOKE This determines whether or not TLS certificate revocation checks should be performed. This only works on Windows. http.ssl-version Type: string or min/max table Default: none Environment: CARGO_HTTP_SSL_VERSION This sets the minimum TLS version to use. It takes a string, with one of the possible values of "default" , "tlsv1" , "tlsv1.0" , "tlsv1.1" , "tlsv1.2" , or "tlsv1.3" . This may alternatively take a table with two keys, min and max , which each take a string value of the same kind that specifies the minimum and maximum range of TLS versions to use. The default is a minimum version of "tlsv1.0" and a max of the newest version supported on your platform, typically "tlsv1.3" . http.low-speed-limit Type: integer Default: 10 Environment: CARGO_HTTP_LOW_SPEED_LIMIT This setting controls timeout behavior for slow connections. If the average transfer speed in bytes per second is below the given value for http.timeout seconds (default 30 seconds), then the connection is considered too slow and Cargo will abort and retry. http.multiplexing Type: boolean Default: true Environment: CARGO_HTTP_MULTIPLEXING When true , Cargo will attempt to use the HTTP2 protocol with multiplexing. This allows multiple requests to use the same connection, usually improving performance when fetching multiple files. If false , Cargo will use HTTP 1.1 without pipelining. http.user-agent Type: string Default: Cargo’s version Environment: CARGO_HTTP_USER_AGENT Specifies a custom user-agent header to use. The default if not specified is a string that includes Cargo’s version. [install] The [install] table defines defaults for the cargo install command. install.root Type: string (path) Default: Cargo’s home directory Environment: CARGO_INSTALL_ROOT Sets the path to the root directory for installing executables for cargo install . Executables go into a bin directory underneath the root. To track information of installed executables, some extra files, such as .crates.toml and .crates2.json , are also created under this root. The default if not specified is Cargo’s home directory (default .cargo in your home directory). Can be overridden with the --root command-line option. [net] The [net] table controls networking configuration. net.retry Type: integer Default: 3 Environment: CARGO_NET_RETRY Number of times to retry possibly spurious network errors. net.git-fetch-with-cli Type: boolean Default: false Environment: CARGO_NET_GIT_FETCH_WITH_CLI If this is true , then Cargo will use the git executable to fetch registry indexes and git dependencies. If false , then it uses a built-in git library. Setting this to true can be helpful if you have special authentication requirements that Cargo does not support. See Git Authentication for more information about setting up git authentication. net.offline Type: boolean Default: false Environment: CARGO_NET_OFFLINE If this is true , then Cargo will avoid accessing the network, and attempt to proceed with locally cached data. If false , Cargo will access the network as needed, and generate an error if it encounters a network error. Can be overridden with the --offline command-line option. net.ssh The [net.ssh] table contains settings for SSH connections. net.ssh.known-hosts Type: array of strings Default: see description Environment: not supported The known-hosts array contains a list of SSH host keys that should be accepted as valid when connecting to an SSH server (such as for SSH git dependencies). Each entry should be a string in a format similar to OpenSSH known_hosts files. Each string should start with one or more hostnames separated by commas, a space, the key type name, a space, and the base64-encoded key. For example: [net.ssh] known-hosts = [ "example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFO4Q5T0UV0SQevair9PFwoxY9dl4pQl3u5phoqJH3cF" ] Cargo will attempt to load known hosts keys from common locations supported in OpenSSH, and will join those with any listed in a Cargo configuration file. If any matching entry has the correct key, the connection will be allowed. Cargo comes with the host keys for github.com built-in. If those ever change, you can add the new keys to the config or known_hosts file. See Git Authentication for more details. [patch] Just as you can override dependencies using [patch] in Cargo.toml , you can override them in the cargo configuration file to apply those patches to any affected build. The format is identical to the one used in Cargo.toml . Since .cargo/config.toml files are not usually checked into source control, you should prefer patching using Cargo.toml where possible to ensure that other developers can compile your crate in their own environments. Patching through cargo configuration files is generally only appropriate when the patch section is automatically generated by an external build tool. If a given dependency is patched both in a cargo configuration file and a Cargo.toml file, the patch in the configuration file is used. If multiple configuration files patch the same dependency, standard cargo configuration merging is used, which prefers the value defined closest to the current directory, with $HOME/.cargo/config.toml taking the lowest precedence. Relative path dependencies in such a [patch] section are resolved relative to the configuration file they appear in. [profile] The [profile] table can be used to globally change profile settings, and override settings specified in Cargo.toml . It has the same syntax and options as profiles specified in Cargo.toml . See the Profiles chapter for details about the options. [profile.<name>.build-override] Environment: CARGO_PROFILE_<name>_BUILD_OVERRIDE_<key> The build-override table overrides settings for build scripts, proc macros, and their dependencies. It has the same keys as a normal profile. See the overrides section for more details. [profile.<name>.package.<name>] Environment: not supported The package table overrides settings for specific packages. It has the same keys as a normal profile, minus the panic , lto , and rpath settings. See the overrides section for more details. profile.<name>.codegen-units Type: integer Default: See profile docs. Environment: CARGO_PROFILE_<name>_CODEGEN_UNITS See codegen-units . profile.<name>.debug Type: integer or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG See debug . profile.<name>.split-debuginfo Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_SPLIT_DEBUGINFO See split-debuginfo . profile.<name>.debug-assertions Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG_ASSERTIONS See debug-assertions . profile.<name>.incremental Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_INCREMENTAL See incremental . profile.<name>.lto Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_LTO See lto . profile.<name>.overflow-checks Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_OVERFLOW_CHECKS See overflow-checks . profile.<name>.opt-level Type: integer or string Default: See profile docs. Environment: CARGO_PROFILE_<name>_OPT_LEVEL See opt-level . profile.<name>.panic Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_PANIC See panic . profile.<name>.rpath Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_RPATH See rpath . profile.<name>.strip Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_STRIP See strip . [resolver] The [resolver] table overrides dependency resolution behavior for local development (e.g. excludes cargo install ). resolver.incompatible-rust-versions Type: string Default: See resolver docs Environment: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS When resolving which version of a dependency to use, select how versions with incompatible package.rust-version s are treated. Values include: allow : treat rust-version -incompatible versions like any other version fallback : only consider rust-version -incompatible versions if no other version matched Can be overridden with --ignore-rust-version CLI option Setting the dependency’s version requirement higher than any version with a compatible rust-version Specifying the version to cargo update with --precise See the resolver chapter for more details. MSRV: allow is supported on any version fallback is respected as of 1.84 [registries] The [registries] table is used for specifying additional registries . It consists of a sub-table for each named registry. registries.<name>.index Type: string (url) Default: none Environment: CARGO_REGISTRIES_<name>_INDEX Specifies the URL of the index for the registry. registries.<name>.token Type: string Default: none Environment: CARGO_REGISTRIES_<name>_TOKEN Specifies the authentication token for the given registry. This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registries.<name>.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRIES_<name>_CREDENTIAL_PROVIDER Specifies the credential provider for the given registry. If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registries.crates-io.protocol Type: string Default: "sparse" Environment: CARGO_REGISTRIES_CRATES_IO_PROTOCOL Specifies the protocol used to access crates.io. Allowed values are git or sparse . git causes Cargo to clone the entire index of all packages ever published to crates.io from https://github.com/rust-lang/crates.io-index/ . This can have performance implications due to the size of the index. sparse is a newer protocol which uses HTTPS to download only what is necessary from https://index.crates.io/ . This can result in a significant performance improvement for resolving new dependencies in most situations. More information about registry protocols may be found in the Registries chapter . [registry] The [registry] table controls the default registry used when one is not specified. registry.index This value is no longer accepted and should not be used. registry.default Type: string Default: "crates-io" Environment: CARGO_REGISTRY_DEFAULT The name of the registry (from the registries table ) to use by default for registry commands like cargo publish . Can be overridden with the --registry command-line option. registry.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRY_CREDENTIAL_PROVIDER Specifies the credential provider for crates.io . If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registry.token Type: string Default: none Environment: CARGO_REGISTRY_TOKEN Specifies the authentication token for crates.io . This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registry.global-credential-providers Type: array Default: ["cargo:token"] Environment: CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS Specifies the list of global credential providers. If credential provider is not set for a specific registry using registries.<name>.credential-provider , Cargo will use the credential providers in this list. Providers toward the end of the list have precedence. Path and arguments are split on spaces. If the path or arguments contains spaces, the credential provider should be defined in the [credential-alias] table and referenced here by its alias. See Registry Authentication for more information. [source] The [source] table defines the registry sources available. See Source Replacement for more information. It consists of a sub-table for each named source. A source should only define one kind (directory, registry, local-registry, or git). source.<name>.replace-with Type: string Default: none Environment: not supported If set, replace this source with the given named source or named registry. source.<name>.directory Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a directory source. source.<name>.registry Type: string (url) Default: none Environment: not supported Sets the URL to use for a registry source. source.<name>.local-registry Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a local registry source. source.<name>.git Type: string (url) Default: none Environment: not supported Sets the URL to use for a git repository source. source.<name>.branch Type: string Default: none Environment: not supported Sets the branch name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.tag Type: string Default: none Environment: not supported Sets the tag name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.rev Type: string Default: none Environment: not supported Sets the revision to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. [target] The [target] table is used for specifying settings for specific platform targets. It consists of a sub-table which is either a platform triple or a cfg() expression . The given values will be used if the target platform matches either the <triple> value or the <cfg> expression. [target.thumbv7m-none-eabi] linker = "arm-none-eabi-gcc" runner = "my-emulator" rustflags = ["…", "…"] [target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "my-arm-wrapper" rustflags = ["…", "…"] cfg values come from those built-in to the compiler (run rustc --print=cfg to view) and extra --cfg flags passed to rustc (such as those defined in RUSTFLAGS ). Do not try to match on debug_assertions , test , Cargo features like feature="foo" , or values set by build scripts . If using a target spec JSON file, the <triple> value is the filename stem. For example --target foo/bar.json would match [target.bar] . target.<triple>.ar This option is deprecated and unused. target.<triple>.linker Type: string (program path) Default: none Environment: CARGO_TARGET_<triple>_LINKER Specifies the linker which is passed to rustc (via -C linker ) when the <triple> is being compiled for. By default, the linker is not overridden. target.<cfg>.linker This is similar to the target linker , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.runner Type: string or array of strings ( program path with args ) Default: none Environment: CARGO_TARGET_<triple>_RUNNER If a runner is provided, executables for the target <triple> will be executed by invoking the specified runner with the actual executable passed as an argument. This applies to cargo run , cargo test and cargo bench commands. By default, compiled executables are executed directly. target.<cfg>.runner This is similar to the target runner , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.rustflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustflags for more details on the different ways to specific extra flags. target.<cfg>.rustflags This is similar to the target rustflags , but using a cfg() expression . If several <cfg> and <triple> entries match the current target, the flags are joined together. target.<triple>.rustdocflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTDOCFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustdocflags for more details on the different ways to specific extra flags. target.<triple>.<links> The links sub-table provides a way to override a build script . When specified, the build script for the given links library will not be run, and the given values will be used instead. [target.x86_64-unknown-linux-gnu.foo] rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] The [term] table controls terminal output and interaction. term.quiet Type: boolean Default: false Environment: CARGO_TERM_QUIET Controls whether or not log messages are displayed by Cargo. Specifying the --quiet flag will override and force quiet output. Specifying the --verbose flag will override and disable quiet output. term.verbose Type: boolean Default: false Environment: CARGO_TERM_VERBOSE Controls whether or not extra detailed messages are displayed by Cargo. Specifying the --quiet flag will override and disable verbose output. Specifying the --verbose flag will override and force verbose output. term.color Type: string Default: "auto" Environment: CARGO_TERM_COLOR Controls whether or not colored output is used in the terminal. Possible values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. Can be overridden with the --color command-line option. term.hyperlinks Type: bool Default: auto-detect Environment: CARGO_TERM_HYPERLINKS Controls whether or not hyperlinks are used in the terminal. term.unicode Type: bool Default: auto-detect Environment: CARGO_TERM_UNICODE Control whether output can be rendered using non-ASCII unicode characters. term.progress.when Type: string Default: "auto" Environment: CARGO_TERM_PROGRESS_WHEN Controls whether or not progress bar is shown in the terminal. Possible values: auto (default): Intelligently guess whether to show progress bar. always : Always show progress bar. never : Never show progress bar. term.progress.width Type: integer Default: none Environment: CARGO_TERM_PROGRESS_WIDTH Sets the width for progress bar. term.progress.term-integration Type: bool Default: auto-detect Environment: CARGO_TERM_PROGRESS_TERM_INTEGRATION Report progress to the terminal emulator for display in places like the task bar. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#manifest-options | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://www.mkdocs.org/dev-guide/#developer-guide | Developer Guide - MkDocs MkDocs Home Getting Started User Guide User Guide Installation Writing Your Docs Choosing Your Theme Customizing Your Theme Localizing Your Theme Configuration Command Line Interface Deploying Your Docs Developer Guide Developer Guide Themes Translations Plugins API Reference About Release Notes Contributing License Search Previous Next Edit on GitHub Developer Guide Developer Guide Extending MkDocs The MkDocs Developer Guide provides documentation for developers of third party themes and plugins. Please see the Contributing Guide for information on contributing to MkDocs itself. You can jump directly to a page listed below, or use the next and previous buttons in the navigation bar at the top of the page to move through the documentation in order. Themes Translations Plugins API Reference Copyright © 2014 Tom Christie , Maintained by the MkDocs Team . Documentation built with MkDocs . Search × Close From here you can search these documents. Enter your search terms below. Keyboard Shortcuts × Close Keys Action ? Open this help n Next page p Previous page s Search | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/reference/config.html#environment-variables | Configuration - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book Configuration This document explains how Cargo’s configuration system works, as well as available keys or configuration. For configuration of a package through its manifest, see the manifest format . Hierarchical structure Cargo allows local configuration for a particular package as well as global configuration. It looks for configuration files in the current directory and all parent directories. If, for example, Cargo were invoked in /projects/foo/bar/baz , then the following configuration files would be probed for and unified in this order: /projects/foo/bar/baz/.cargo/config.toml /projects/foo/bar/.cargo/config.toml /projects/foo/.cargo/config.toml /projects/.cargo/config.toml /.cargo/config.toml $CARGO_HOME/config.toml which defaults to: Windows: %USERPROFILE%\.cargo\config.toml Unix: $HOME/.cargo/config.toml With this structure, you can specify configuration per-package, and even possibly check it into version control. You can also specify personal defaults with a configuration file in your home directory. If a key is specified in multiple config files, the values will get merged together. Numbers, strings, and booleans will use the value in the deeper config directory taking precedence over ancestor directories, where the home directory is the lowest priority. Arrays will be joined together with higher precedence items being placed later in the merged array. At present, when being invoked from a workspace, Cargo does not read config files from crates within the workspace. i.e. if a workspace has two crates in it, named /projects/foo/bar/baz/mylib and /projects/foo/bar/baz/mybin , and there are Cargo configs at /projects/foo/bar/baz/mylib/.cargo/config.toml and /projects/foo/bar/baz/mybin/.cargo/config.toml , Cargo does not read those configuration files if it is invoked from the workspace root ( /projects/foo/bar/baz/ ). Note: Cargo also reads config files without the .toml extension, such as .cargo/config . Support for the .toml extension was added in version 1.39 and is the preferred form. If both files exist, Cargo will use the file without the extension. Configuration format Configuration files are written in the TOML format (like the manifest), with simple key-value pairs inside of sections (tables). The following is a quick overview of all settings, with detailed descriptions found below. paths = ["/path/to/override"] # path dependency overrides [alias] # command aliases b = "build" c = "check" t = "test" r = "run" rr = "run --release" recursive_example = "rr --example recursions" space_example = ["run", "--release", "--", "\"command list\""] [build] jobs = 1 # number of parallel jobs, defaults to # of CPUs rustc = "rustc" # the rust compiler tool rustc-wrapper = "…" # run this wrapper instead of `rustc` rustc-workspace-wrapper = "…" # run this wrapper instead of `rustc` for workspace members rustdoc = "rustdoc" # the doc generator tool target = "triple" # build for the target triple (ignored by `cargo install`) target-dir = "target" # path of where to place generated artifacts build-dir = "target" # path of where to place intermediate build artifacts rustflags = ["…", "…"] # custom flags to pass to all compiler invocations rustdocflags = ["…", "…"] # custom flags to pass to rustdoc incremental = true # whether or not to enable incremental compilation dep-info-basedir = "…" # path for the base directory for targets in depfiles [credential-alias] # Provides a way to define aliases for credential providers. my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] [doc] browser = "chromium" # browser to use with `cargo doc --open`, # overrides the `BROWSER` environment variable [env] # Set ENV_VAR_NAME=value for any process run by Cargo ENV_VAR_NAME = "value" # Set even if already present in environment ENV_VAR_NAME_2 = { value = "value", force = true } # `value` is relative to the parent of `.cargo/config.toml`, env var will be the full absolute path ENV_VAR_NAME_3 = { value = "relative/path", relative = true } [future-incompat-report] frequency = 'always' # when to display a notification about a future incompat report [cache] auto-clean-frequency = "1 day" # How often to perform automatic cache cleaning [cargo-new] vcs = "none" # VCS to use ('git', 'hg', 'pijul', 'fossil', 'none') [http] debug = false # HTTP debugging proxy = "host:port" # HTTP proxy in libcurl format ssl-version = "tlsv1.3" # TLS version to use ssl-version.max = "tlsv1.3" # maximum TLS version ssl-version.min = "tlsv1.1" # minimum TLS version timeout = 30 # timeout for each HTTP request, in seconds low-speed-limit = 10 # network timeout threshold (bytes/sec) cainfo = "cert.pem" # path to Certificate Authority (CA) bundle proxy-cainfo = "cert.pem" # path to proxy Certificate Authority (CA) bundle check-revoke = true # check for SSL certificate revocation multiplexing = true # HTTP/2 multiplexing user-agent = "…" # the user-agent header [install] root = "/some/path" # `cargo install` destination directory [net] retry = 3 # network retries git-fetch-with-cli = true # use the `git` executable for git operations offline = true # do not access the network [net.ssh] known-hosts = ["..."] # known SSH host keys [patch.<registry>] # Same keys as for [patch] in Cargo.toml [profile.<name>] # Modify profile settings via config. inherits = "dev" # Inherits settings from [profile.dev]. opt-level = 0 # Optimization level. debug = true # Include debug info. split-debuginfo = '...' # Debug info splitting behavior. strip = "none" # Removes symbols or debuginfo. debug-assertions = true # Enables debug assertions. overflow-checks = true # Enables runtime integer overflow checks. lto = false # Sets link-time optimization. panic = 'unwind' # The panic strategy. incremental = true # Incremental compilation. codegen-units = 16 # Number of code generation units. rpath = false # Sets the rpath linking option. [profile.<name>.build-override] # Overrides build-script settings. # Same keys for a normal profile. [profile.<name>.package.<name>] # Override profile for a package. # Same keys for a normal profile (minus `panic`, `lto`, and `rpath`). [resolver] incompatible-rust-versions = "allow" # Specifies how resolver reacts to these [registries.<name>] # registries other than crates.io index = "…" # URL of the registry index token = "…" # authentication token for the registry credential-provider = "cargo:token" # The credential provider for this registry. [registries.crates-io] protocol = "sparse" # The protocol to use to access crates.io. [registry] default = "…" # name of the default registry token = "…" # authentication token for crates.io credential-provider = "cargo:token" # The credential provider for crates.io. global-credential-providers = ["cargo:token"] # The credential providers to use by default. [source.<name>] # source definition and replacement replace-with = "…" # replace this source with the given named source directory = "…" # path to a directory source registry = "…" # URL to a registry source local-registry = "…" # path to a local registry source git = "…" # URL of a git repository source branch = "…" # branch name for the git repository tag = "…" # tag name for the git repository rev = "…" # revision for the git repository [target.<triple>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` rustdocflags = ["…", "…"] # custom flags for `rustdoc` [target.<cfg>] linker = "…" # linker to use runner = "…" # wrapper to run executables rustflags = ["…", "…"] # custom flags for `rustc` [target.<triple>.<links>] # `links` build script override rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] quiet = false # whether cargo output is quiet verbose = false # whether cargo provides verbose output color = 'auto' # whether cargo colorizes output hyperlinks = true # whether cargo inserts links into output unicode = true # whether cargo can render output using non-ASCII unicode characters progress.when = 'auto' # whether cargo shows progress bar progress.width = 80 # width of progress bar progress.term-integration = true # whether cargo reports progress to terminal emulator Environment variables Cargo can also be configured through environment variables in addition to the TOML configuration files. For each configuration key of the form foo.bar the environment variable CARGO_FOO_BAR can also be used to define the value. Keys are converted to uppercase, dots and dashes are converted to underscores. For example the target.x86_64-unknown-linux-gnu.runner key can also be defined by the CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER environment variable. Environment variables will take precedence over TOML configuration files. Currently only integer, boolean, string and some array values are supported to be defined by environment variables. Descriptions below indicate which keys support environment variables and otherwise they are not supported due to technical issues . In addition to the system above, Cargo recognizes a few other specific environment variables . Command-line overrides Cargo also accepts arbitrary configuration overrides through the --config command-line option. The argument should be in TOML syntax of KEY=VALUE or provided as a path to an extra configuration file: # With `KEY=VALUE` in TOML syntax cargo --config net.git-fetch-with-cli=true fetch # With a path to a configuration file cargo --config ./path/to/my/extra-config.toml fetch The --config option may be specified multiple times, in which case the values are merged in left-to-right order, using the same merging logic that is used when multiple configuration files apply. Configuration values specified this way take precedence over environment variables, which take precedence over configuration files. When the --config option is provided as an extra configuration file, The configuration file loaded this way follow the same precedence rules as other options specified directly with --config . Some examples of what it looks like using Bourne shell syntax: # Most shells will require escaping. cargo --config http.proxy=\"http://example.com\" … # Spaces may be used. cargo --config "net.git-fetch-with-cli = true" … # TOML array example. Single quotes make it easier to read and write. cargo --config 'build.rustdocflags = ["--html-in-header", "header.html"]' … # Example of a complex TOML key. cargo --config "target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))'.runner = 'my-runner'" … # Example of overriding a profile setting. cargo --config profile.dev.package.image.opt-level=3 … Config-relative paths Paths in config files may be absolute, relative, or a bare name without any path separators. Paths for executables without a path separator will use the PATH environment variable to search for the executable. Paths for non-executables will be relative to where the config value is defined. In particular, rules are: For environment variables, paths are relative to the current working directory. For config values loaded directly from the --config KEY=VALUE option, paths are relative to the current working directory. For config files, paths are relative to the parent directory of the directory where the config files were defined, no matter those files are from either the hierarchical probing or the --config <path> option. Note: To maintain consistency with existing .cargo/config.toml probing behavior, it is by design that a path in a config file passed via --config <path> is also relative to two levels up from the config file itself. To avoid unexpected results, the rule of thumb is putting your extra config files at the same level of discovered .cargo/config.toml in your project. For instance, given a project /my/project , it is recommended to put config files under /my/project/.cargo or a new directory at the same level, such as /my/project/.config . # Relative path examples. [target.x86_64-unknown-linux-gnu] runner = "foo" # Searches `PATH` for `foo`. [source.vendored-sources] # Directory is relative to the parent where `.cargo/config.toml` is located. # For example, `/my/project/.cargo/config.toml` would result in `/my/project/vendor`. directory = "vendor" Executable paths with arguments Some Cargo commands invoke external programs, which can be configured as a path and some number of arguments. The value may be an array of strings like ['/path/to/program', 'somearg'] or a space-separated string like '/path/to/program somearg' . If the path to the executable contains a space, the list form must be used. If Cargo is passing other arguments to the program such as a path to open or run, they will be passed after the last specified argument in the value of an option of this format. If the specified program does not have path separators, Cargo will search PATH for its executable. Credentials Configuration values with sensitive information are stored in the $CARGO_HOME/credentials.toml file. This file is automatically created and updated by cargo login and cargo logout when using the cargo:token credential provider. Tokens are used by some Cargo commands such as cargo publish for authenticating with remote registries. Care should be taken to protect the tokens and to keep them secret. It follows the same format as Cargo config files. [registry] token = "…" # Access token for crates.io [registries.<name>] token = "…" # Access token for the named registry As with most other config values, tokens may be specified with environment variables. The token for crates.io may be specified with the CARGO_REGISTRY_TOKEN environment variable. Tokens for other registries may be specified with environment variables of the form CARGO_REGISTRIES_<name>_TOKEN where <name> is the name of the registry in all capital letters. Note: Cargo also reads and writes credential files without the .toml extension, such as .cargo/credentials . Support for the .toml extension was added in version 1.39. In version 1.68, Cargo writes to the file with the extension by default. However, for backward compatibility reason, when both files exist, Cargo will read and write the file without the extension. Configuration keys This section documents all configuration keys. The description for keys with variable parts are annotated with angled brackets like target.<triple> where the <triple> part can be any target triple like target.x86_64-pc-windows-msvc . paths Type: array of strings (paths) Default: none Environment: not supported An array of paths to local packages which are to be used as overrides for dependencies. For more information see the Overriding Dependencies guide . [alias] Type: string or array of strings Default: see below Environment: CARGO_ALIAS_<name> The [alias] table defines CLI command aliases. For example, running cargo b is an alias for running cargo build . Each key in the table is the subcommand, and the value is the actual command to run. The value may be an array of strings, where the first element is the command and the following are arguments. It may also be a string, which will be split on spaces into subcommand and arguments. The following aliases are built-in to Cargo: [alias] b = "build" c = "check" d = "doc" t = "test" r = "run" rm = "remove" Aliases are not allowed to redefine existing built-in commands. Aliases are recursive: [alias] rr = "run --release" recursive_example = "rr --example recursions" [build] The [build] table controls build-time operations and compiler settings. build.jobs Type: integer or string Default: number of logical CPUs Environment: CARGO_BUILD_JOBS Sets the maximum number of compiler processes to run in parallel. If negative, it sets the maximum number of compiler processes to the number of logical CPUs plus provided value. Should not be 0. If a string default is provided, it sets the value back to defaults. Can be overridden with the --jobs CLI option. build.rustc Type: string (program path) Default: "rustc" Environment: CARGO_BUILD_RUSTC or RUSTC Sets the executable to use for rustc . build.rustc-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WRAPPER or RUSTC_WRAPPER Sets a wrapper to execute instead of rustc . The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). build.rustc-workspace-wrapper Type: string (program path) Default: none Environment: CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER or RUSTC_WORKSPACE_WRAPPER Sets a wrapper to execute instead of rustc , for workspace members only. When building a single-package project without workspaces, that package is considered to be the workspace. The first argument passed to the wrapper is the path to the actual executable to use (i.e., build.rustc , if that is set, or "rustc" otherwise). It affects the filename hash so that artifacts produced by the wrapper are cached separately. If both rustc-wrapper and rustc-workspace-wrapper are set, then they will be nested: the final invocation is $RUSTC_WRAPPER $RUSTC_WORKSPACE_WRAPPER $RUSTC . build.rustdoc Type: string (program path) Default: "rustdoc" Environment: CARGO_BUILD_RUSTDOC or RUSTDOC Sets the executable to use for rustdoc . build.target Type: string or array of strings Default: host platform Environment: CARGO_BUILD_TARGET The default target platform triples to compile to. Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. Can be overridden with the --target CLI option. [build] target = ["x86_64-unknown-linux-gnu", "i686-unknown-linux-gnu"] build.target-dir Type: string (path) Default: "target" Environment: CARGO_BUILD_TARGET_DIR or CARGO_TARGET_DIR The path to where all compiler output is placed. The default if not specified is a directory named target located at the root of the workspace. Can be overridden with the --target-dir CLI option. For more information see the build cache documentation . build.build-dir Type: string (path) Default: Defaults to the value of build.target-dir Environment: CARGO_BUILD_BUILD_DIR The directory where intermediate build artifacts will be stored. Intermediate artifacts are produced by Rustc/Cargo during the build process. This option supports path templating. Available template variables: {workspace-root} resolves to root of the current workspace. {cargo-cache-home} resolves to CARGO_HOME {workspace-path-hash} resolves to a hash of the manifest path For more information see the build cache documentation . build.rustflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS or RUSTFLAGS Extra command-line flags to pass to rustc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTFLAGS environment variable. RUSTFLAGS environment variable. All matching target.<triple>.rustflags and target.<cfg>.rustflags config entries joined together. build.rustflags config value. Additional flags may also be passed with the cargo rustc command. If the --target flag (or build.target ) is used, then the flags will only be passed to the compiler for the target. Things being built for the host, such as build scripts or proc macros, will not receive the args. Without --target , the flags will be passed to all compiler invocations (including build scripts and proc macros) because dependencies are shared. If you have args that you do not want to pass to build scripts or proc macros and are building for the host, pass --target with the host triple . It is not recommended to pass in flags that Cargo itself usually manages. For example, the flags driven by profiles are best handled by setting the appropriate profile setting. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.rustdocflags Type: string or array of strings Default: none Environment: CARGO_BUILD_RUSTDOCFLAGS or CARGO_ENCODED_RUSTDOCFLAGS or RUSTDOCFLAGS Extra command-line flags to pass to rustdoc . The value may be an array of strings or a space-separated string. There are four mutually exclusive sources of extra flags. They are checked in order, with the first one being used: CARGO_ENCODED_RUSTDOCFLAGS environment variable. RUSTDOCFLAGS environment variable. All matching target.<triple>.rustdocflags config entries joined together. build.rustdocflags config value. Additional flags may also be passed with the cargo rustdoc command. Caution : Due to the low-level nature of passing flags directly to the compiler, this may cause a conflict with future versions of Cargo which may issue the same or similar flags on its own which may interfere with the flags you specify. This is an area where Cargo may not always be backwards compatible. build.incremental Type: bool Default: from profile Environment: CARGO_BUILD_INCREMENTAL or CARGO_INCREMENTAL Whether or not to perform incremental compilation . The default if not set is to use the value from the profile . Otherwise this overrides the setting of all profiles. The CARGO_INCREMENTAL environment variable can be set to 1 to force enable incremental compilation for all profiles, or 0 to disable it. This env var overrides the config setting. build.dep-info-basedir Type: string (path) Default: none Environment: CARGO_BUILD_DEP_INFO_BASEDIR Strips the given path prefix from dep info file paths. This config setting is intended to convert absolute paths to relative paths for tools that require relative paths. The setting itself is a config-relative path. So, for example, a value of "." would strip all paths starting with the parent directory of the .cargo directory. build.pipelining This option is deprecated and unused. Cargo always has pipelining enabled. [credential-alias] Type: string or array of strings Default: empty Environment: CARGO_CREDENTIAL_ALIAS_<name> The [credential-alias] table defines credential provider aliases. These aliases can be referenced as an element of the registry.global-credential-providers array, or as a credential provider for a specific registry under registries.<NAME>.credential-provider . If specified as a string, the value will be split on spaces into path and arguments. For example, to define an alias called my-alias : [credential-alias] my-alias = ["/usr/bin/cargo-credential-example", "--argument", "value", "--flag"] See Registry Authentication for more information. [doc] The [doc] table defines options for the cargo doc command. doc.browser Type: string or array of strings ( program path with args ) Default: BROWSER environment variable, or, if that is missing, opening the link in a system specific way This option sets the browser to be used by cargo doc , overriding the BROWSER environment variable when opening documentation with the --open option. [cargo-new] The [cargo-new] table defines defaults for the cargo new command. cargo-new.name This option is deprecated and unused. cargo-new.email This option is deprecated and unused. cargo-new.vcs Type: string Default: "git" or "none" Environment: CARGO_CARGO_NEW_VCS Specifies the source control system to use for initializing a new repository. Valid values are git , hg (for Mercurial), pijul , fossil or none to disable this behavior. Defaults to git , or none if already inside a VCS repository. Can be overridden with the --vcs CLI option. [env] The [env] section allows you to set additional environment variables for build scripts, rustc invocations, cargo run and cargo build . [env] OPENSSL_DIR = "/opt/openssl" By default, the variables specified will not override values that already exist in the environment. This behavior can be changed by setting the force flag. Setting the relative flag evaluates the value as a config-relative path that is relative to the parent directory of the .cargo directory that contains the config.toml file. The value of the environment variable will be the full absolute path. [env] TMPDIR = { value = "/home/tmp", force = true } OPENSSL_DIR = { value = "vendor/openssl", relative = true } [future-incompat-report] The [future-incompat-report] table controls setting for future incompat reporting future-incompat-report.frequency Type: string Default: "always" Environment: CARGO_FUTURE_INCOMPAT_REPORT_FREQUENCY Controls how often we display a notification to the terminal when a future incompat report is available. Possible values: always (default): Always display a notification when a command (e.g. cargo build ) produces a future incompat report never : Never display a notification [cache] The [cache] table defines settings for cargo’s caches. Global caches When running cargo commands, Cargo will automatically track which files you are using within the global cache. Periodically, Cargo will delete files that have not been used for some period of time. It will delete files that have to be downloaded from the network if they have not been used in 3 months. Files that can be generated without network access will be deleted if they have not been used in 1 month. The automatic deletion of files only occurs when running commands that are already doing a significant amount of work, such as all of the build commands ( cargo build , cargo test , cargo check , etc.), and cargo fetch . Automatic deletion is disabled if cargo is offline such as with --offline or --frozen to avoid deleting artifacts that may need to be used if you are offline for a long period of time. Note : This tracking is currently only implemented for the global cache in Cargo’s home directory. This includes registry indexes and source files downloaded from registries and git dependencies. Support for tracking build artifacts is not yet implemented, and tracked in cargo#13136 . Additionally, there is an unstable feature to support manually triggering cache cleaning, and to further customize the configuration options. See the Unstable chapter for more information. cache.auto-clean-frequency Type: string Default: "1 day" Environment: CARGO_CACHE_AUTO_CLEAN_FREQUENCY This option defines how often Cargo will automatically delete unused files in the global cache. This does not define how old the files must be, those thresholds are described above . It supports the following settings: "never" — Never deletes old files. "always" — Checks to delete old files every time Cargo runs. An integer followed by “seconds”, “minutes”, “hours”, “days”, “weeks”, or “months” — Checks to delete old files at most the given time frame. [http] The [http] table defines settings for HTTP behavior. This includes fetching crate dependencies and accessing remote git repositories. http.debug Type: boolean Default: false Environment: CARGO_HTTP_DEBUG If true , enables debugging of HTTP requests. The debug information can be seen by setting the CARGO_LOG=network=debug environment variable (or use network=trace for even more information). Be wary when posting logs from this output in a public location. The output may include headers with authentication tokens which you don’t want to leak! Be sure to review logs before posting them. http.proxy Type: string Default: none Environment: CARGO_HTTP_PROXY or HTTPS_PROXY or https_proxy or http_proxy Sets an HTTP and HTTPS proxy to use. The format is in libcurl format as in [protocol://]host[:port] . If not set, Cargo will also check the http.proxy setting in your global git configuration. If none of those are set, the HTTPS_PROXY or https_proxy environment variables set the proxy for HTTPS requests, and http_proxy sets it for HTTP requests. http.timeout Type: integer Default: 30 Environment: CARGO_HTTP_TIMEOUT or HTTP_TIMEOUT Sets the timeout for each HTTP request, in seconds. http.cainfo Type: string (path) Default: none Environment: CARGO_HTTP_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify TLS certificates. If not specified, Cargo attempts to use the system certificates. http.proxy-cainfo Type: string (path) Default: falls back to http.cainfo if not set Environment: CARGO_HTTP_PROXY_CAINFO Path to a Certificate Authority (CA) bundle file, used to verify proxy TLS certificates. http.check-revoke Type: boolean Default: true (Windows) false (all others) Environment: CARGO_HTTP_CHECK_REVOKE This determines whether or not TLS certificate revocation checks should be performed. This only works on Windows. http.ssl-version Type: string or min/max table Default: none Environment: CARGO_HTTP_SSL_VERSION This sets the minimum TLS version to use. It takes a string, with one of the possible values of "default" , "tlsv1" , "tlsv1.0" , "tlsv1.1" , "tlsv1.2" , or "tlsv1.3" . This may alternatively take a table with two keys, min and max , which each take a string value of the same kind that specifies the minimum and maximum range of TLS versions to use. The default is a minimum version of "tlsv1.0" and a max of the newest version supported on your platform, typically "tlsv1.3" . http.low-speed-limit Type: integer Default: 10 Environment: CARGO_HTTP_LOW_SPEED_LIMIT This setting controls timeout behavior for slow connections. If the average transfer speed in bytes per second is below the given value for http.timeout seconds (default 30 seconds), then the connection is considered too slow and Cargo will abort and retry. http.multiplexing Type: boolean Default: true Environment: CARGO_HTTP_MULTIPLEXING When true , Cargo will attempt to use the HTTP2 protocol with multiplexing. This allows multiple requests to use the same connection, usually improving performance when fetching multiple files. If false , Cargo will use HTTP 1.1 without pipelining. http.user-agent Type: string Default: Cargo’s version Environment: CARGO_HTTP_USER_AGENT Specifies a custom user-agent header to use. The default if not specified is a string that includes Cargo’s version. [install] The [install] table defines defaults for the cargo install command. install.root Type: string (path) Default: Cargo’s home directory Environment: CARGO_INSTALL_ROOT Sets the path to the root directory for installing executables for cargo install . Executables go into a bin directory underneath the root. To track information of installed executables, some extra files, such as .crates.toml and .crates2.json , are also created under this root. The default if not specified is Cargo’s home directory (default .cargo in your home directory). Can be overridden with the --root command-line option. [net] The [net] table controls networking configuration. net.retry Type: integer Default: 3 Environment: CARGO_NET_RETRY Number of times to retry possibly spurious network errors. net.git-fetch-with-cli Type: boolean Default: false Environment: CARGO_NET_GIT_FETCH_WITH_CLI If this is true , then Cargo will use the git executable to fetch registry indexes and git dependencies. If false , then it uses a built-in git library. Setting this to true can be helpful if you have special authentication requirements that Cargo does not support. See Git Authentication for more information about setting up git authentication. net.offline Type: boolean Default: false Environment: CARGO_NET_OFFLINE If this is true , then Cargo will avoid accessing the network, and attempt to proceed with locally cached data. If false , Cargo will access the network as needed, and generate an error if it encounters a network error. Can be overridden with the --offline command-line option. net.ssh The [net.ssh] table contains settings for SSH connections. net.ssh.known-hosts Type: array of strings Default: see description Environment: not supported The known-hosts array contains a list of SSH host keys that should be accepted as valid when connecting to an SSH server (such as for SSH git dependencies). Each entry should be a string in a format similar to OpenSSH known_hosts files. Each string should start with one or more hostnames separated by commas, a space, the key type name, a space, and the base64-encoded key. For example: [net.ssh] known-hosts = [ "example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFO4Q5T0UV0SQevair9PFwoxY9dl4pQl3u5phoqJH3cF" ] Cargo will attempt to load known hosts keys from common locations supported in OpenSSH, and will join those with any listed in a Cargo configuration file. If any matching entry has the correct key, the connection will be allowed. Cargo comes with the host keys for github.com built-in. If those ever change, you can add the new keys to the config or known_hosts file. See Git Authentication for more details. [patch] Just as you can override dependencies using [patch] in Cargo.toml , you can override them in the cargo configuration file to apply those patches to any affected build. The format is identical to the one used in Cargo.toml . Since .cargo/config.toml files are not usually checked into source control, you should prefer patching using Cargo.toml where possible to ensure that other developers can compile your crate in their own environments. Patching through cargo configuration files is generally only appropriate when the patch section is automatically generated by an external build tool. If a given dependency is patched both in a cargo configuration file and a Cargo.toml file, the patch in the configuration file is used. If multiple configuration files patch the same dependency, standard cargo configuration merging is used, which prefers the value defined closest to the current directory, with $HOME/.cargo/config.toml taking the lowest precedence. Relative path dependencies in such a [patch] section are resolved relative to the configuration file they appear in. [profile] The [profile] table can be used to globally change profile settings, and override settings specified in Cargo.toml . It has the same syntax and options as profiles specified in Cargo.toml . See the Profiles chapter for details about the options. [profile.<name>.build-override] Environment: CARGO_PROFILE_<name>_BUILD_OVERRIDE_<key> The build-override table overrides settings for build scripts, proc macros, and their dependencies. It has the same keys as a normal profile. See the overrides section for more details. [profile.<name>.package.<name>] Environment: not supported The package table overrides settings for specific packages. It has the same keys as a normal profile, minus the panic , lto , and rpath settings. See the overrides section for more details. profile.<name>.codegen-units Type: integer Default: See profile docs. Environment: CARGO_PROFILE_<name>_CODEGEN_UNITS See codegen-units . profile.<name>.debug Type: integer or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG See debug . profile.<name>.split-debuginfo Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_SPLIT_DEBUGINFO See split-debuginfo . profile.<name>.debug-assertions Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_DEBUG_ASSERTIONS See debug-assertions . profile.<name>.incremental Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_INCREMENTAL See incremental . profile.<name>.lto Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_LTO See lto . profile.<name>.overflow-checks Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_OVERFLOW_CHECKS See overflow-checks . profile.<name>.opt-level Type: integer or string Default: See profile docs. Environment: CARGO_PROFILE_<name>_OPT_LEVEL See opt-level . profile.<name>.panic Type: string Default: See profile docs. Environment: CARGO_PROFILE_<name>_PANIC See panic . profile.<name>.rpath Type: boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_RPATH See rpath . profile.<name>.strip Type: string or boolean Default: See profile docs. Environment: CARGO_PROFILE_<name>_STRIP See strip . [resolver] The [resolver] table overrides dependency resolution behavior for local development (e.g. excludes cargo install ). resolver.incompatible-rust-versions Type: string Default: See resolver docs Environment: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS When resolving which version of a dependency to use, select how versions with incompatible package.rust-version s are treated. Values include: allow : treat rust-version -incompatible versions like any other version fallback : only consider rust-version -incompatible versions if no other version matched Can be overridden with --ignore-rust-version CLI option Setting the dependency’s version requirement higher than any version with a compatible rust-version Specifying the version to cargo update with --precise See the resolver chapter for more details. MSRV: allow is supported on any version fallback is respected as of 1.84 [registries] The [registries] table is used for specifying additional registries . It consists of a sub-table for each named registry. registries.<name>.index Type: string (url) Default: none Environment: CARGO_REGISTRIES_<name>_INDEX Specifies the URL of the index for the registry. registries.<name>.token Type: string Default: none Environment: CARGO_REGISTRIES_<name>_TOKEN Specifies the authentication token for the given registry. This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registries.<name>.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRIES_<name>_CREDENTIAL_PROVIDER Specifies the credential provider for the given registry. If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registries.crates-io.protocol Type: string Default: "sparse" Environment: CARGO_REGISTRIES_CRATES_IO_PROTOCOL Specifies the protocol used to access crates.io. Allowed values are git or sparse . git causes Cargo to clone the entire index of all packages ever published to crates.io from https://github.com/rust-lang/crates.io-index/ . This can have performance implications due to the size of the index. sparse is a newer protocol which uses HTTPS to download only what is necessary from https://index.crates.io/ . This can result in a significant performance improvement for resolving new dependencies in most situations. More information about registry protocols may be found in the Registries chapter . [registry] The [registry] table controls the default registry used when one is not specified. registry.index This value is no longer accepted and should not be used. registry.default Type: string Default: "crates-io" Environment: CARGO_REGISTRY_DEFAULT The name of the registry (from the registries table ) to use by default for registry commands like cargo publish . Can be overridden with the --registry command-line option. registry.credential-provider Type: string or array of path and arguments Default: none Environment: CARGO_REGISTRY_CREDENTIAL_PROVIDER Specifies the credential provider for crates.io . If not set, the providers in registry.global-credential-providers will be used. If specified as a string, path and arguments will be split on spaces. For paths or arguments that contain spaces, use an array. If the value exists in the [credential-alias] table, the alias will be used. See Registry Authentication for more information. registry.token Type: string Default: none Environment: CARGO_REGISTRY_TOKEN Specifies the authentication token for crates.io . This value should only appear in the credentials file. This is used for registry commands like cargo publish that require authentication. Can be overridden with the --token command-line option. registry.global-credential-providers Type: array Default: ["cargo:token"] Environment: CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS Specifies the list of global credential providers. If credential provider is not set for a specific registry using registries.<name>.credential-provider , Cargo will use the credential providers in this list. Providers toward the end of the list have precedence. Path and arguments are split on spaces. If the path or arguments contains spaces, the credential provider should be defined in the [credential-alias] table and referenced here by its alias. See Registry Authentication for more information. [source] The [source] table defines the registry sources available. See Source Replacement for more information. It consists of a sub-table for each named source. A source should only define one kind (directory, registry, local-registry, or git). source.<name>.replace-with Type: string Default: none Environment: not supported If set, replace this source with the given named source or named registry. source.<name>.directory Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a directory source. source.<name>.registry Type: string (url) Default: none Environment: not supported Sets the URL to use for a registry source. source.<name>.local-registry Type: string (path) Default: none Environment: not supported Sets the path to a directory to use as a local registry source. source.<name>.git Type: string (url) Default: none Environment: not supported Sets the URL to use for a git repository source. source.<name>.branch Type: string Default: none Environment: not supported Sets the branch name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.tag Type: string Default: none Environment: not supported Sets the tag name to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. source.<name>.rev Type: string Default: none Environment: not supported Sets the revision to use for a git repository. If none of branch , tag , or rev is set, defaults to the master branch. [target] The [target] table is used for specifying settings for specific platform targets. It consists of a sub-table which is either a platform triple or a cfg() expression . The given values will be used if the target platform matches either the <triple> value or the <cfg> expression. [target.thumbv7m-none-eabi] linker = "arm-none-eabi-gcc" runner = "my-emulator" rustflags = ["…", "…"] [target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "my-arm-wrapper" rustflags = ["…", "…"] cfg values come from those built-in to the compiler (run rustc --print=cfg to view) and extra --cfg flags passed to rustc (such as those defined in RUSTFLAGS ). Do not try to match on debug_assertions , test , Cargo features like feature="foo" , or values set by build scripts . If using a target spec JSON file, the <triple> value is the filename stem. For example --target foo/bar.json would match [target.bar] . target.<triple>.ar This option is deprecated and unused. target.<triple>.linker Type: string (program path) Default: none Environment: CARGO_TARGET_<triple>_LINKER Specifies the linker which is passed to rustc (via -C linker ) when the <triple> is being compiled for. By default, the linker is not overridden. target.<cfg>.linker This is similar to the target linker , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.runner Type: string or array of strings ( program path with args ) Default: none Environment: CARGO_TARGET_<triple>_RUNNER If a runner is provided, executables for the target <triple> will be executed by invoking the specified runner with the actual executable passed as an argument. This applies to cargo run , cargo test and cargo bench commands. By default, compiled executables are executed directly. target.<cfg>.runner This is similar to the target runner , but using a cfg() expression . If both a <triple> and <cfg> runner match, the <triple> will take precedence. It is an error if more than one <cfg> runner matches the current target. target.<triple>.rustflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustflags for more details on the different ways to specific extra flags. target.<cfg>.rustflags This is similar to the target rustflags , but using a cfg() expression . If several <cfg> and <triple> entries match the current target, the flags are joined together. target.<triple>.rustdocflags Type: string or array of strings Default: none Environment: CARGO_TARGET_<triple>_RUSTDOCFLAGS Passes a set of custom flags to the compiler for this <triple> . The value may be an array of strings or a space-separated string. See build.rustdocflags for more details on the different ways to specific extra flags. target.<triple>.<links> The links sub-table provides a way to override a build script . When specified, the build script for the given links library will not be run, and the given values will be used instead. [target.x86_64-unknown-linux-gnu.foo] rustc-link-lib = ["foo"] rustc-link-search = ["/path/to/foo"] rustc-flags = "-L /some/path" rustc-cfg = ['key="value"'] rustc-env = {key = "value"} rustc-cdylib-link-arg = ["…"] metadata_key1 = "value" metadata_key2 = "value" [term] The [term] table controls terminal output and interaction. term.quiet Type: boolean Default: false Environment: CARGO_TERM_QUIET Controls whether or not log messages are displayed by Cargo. Specifying the --quiet flag will override and force quiet output. Specifying the --verbose flag will override and disable quiet output. term.verbose Type: boolean Default: false Environment: CARGO_TERM_VERBOSE Controls whether or not extra detailed messages are displayed by Cargo. Specifying the --quiet flag will override and disable verbose output. Specifying the --verbose flag will override and force verbose output. term.color Type: string Default: "auto" Environment: CARGO_TERM_COLOR Controls whether or not colored output is used in the terminal. Possible values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. Can be overridden with the --color command-line option. term.hyperlinks Type: bool Default: auto-detect Environment: CARGO_TERM_HYPERLINKS Controls whether or not hyperlinks are used in the terminal. term.unicode Type: bool Default: auto-detect Environment: CARGO_TERM_UNICODE Control whether output can be rendered using non-ASCII unicode characters. term.progress.when Type: string Default: "auto" Environment: CARGO_TERM_PROGRESS_WHEN Controls whether or not progress bar is shown in the terminal. Possible values: auto (default): Intelligently guess whether to show progress bar. always : Always show progress bar. never : Never show progress bar. term.progress.width Type: integer Default: none Environment: CARGO_TERM_PROGRESS_WIDTH Sets the width for progress bar. term.progress.term-integration Type: bool Default: auto-detect Environment: CARGO_TERM_PROGRESS_TERM_INTEGRATION Report progress to the terminal emulator for display in places like the task bar. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package---no-verify | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package--p | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.instagram.com%2F&h=AT2UhsRXmALv-lvf1M3VlUiNYmBrFA0YZU-k3rElKZ4c-KFKLj47Q_S2TSSYWwMyXFZ7xG-ionlBKD40yrzTYIhoT9qhS7FHEiMYke9us0EMpteHvi-mHYMeCZxb5Q4SLZt9Q1VJzgH7UHiv | Facebook Facebook 이메일 또는 휴대폰 비밀번호 계정을 잊으셨나요? 새 계정 만들기 일시적으로 차단됨 일시적으로 차단됨 회원님의 이 기능 사용 속도가 너무 빠른 것 같습니다. 이 기능 사용에서 일시적으로 차단되었습니다. Back 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch 가입하기 로그인 Messenger Facebook Lite 동영상 Meta Pay Meta 스토어 Meta Quest Ray-Ban Meta Meta AI Meta AI 콘텐츠 더 보기 Instagram Threads 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 Meta © 2026 | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#exit-status | cargo package - The Cargo Book Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help Auto Light Rust Coal Navy Ayu The Cargo Book cargo-package(1) NAME cargo-package — Assemble the local package into a distributable tarball SYNOPSIS cargo package [ options ] DESCRIPTION This command will create a distributable, compressed .crate file with the source code of the package in the current directory. The resulting file will be stored in the target/package directory. This performs the following steps: Load and check the current workspace, performing some basic checks. Path dependencies are not allowed unless they have a version key. Cargo will ignore the path key for dependencies in published packages. dev-dependencies do not have this restriction. Create the compressed .crate file. The original Cargo.toml file is rewritten and normalized. [patch] , [replace] , and [workspace] sections are removed from the manifest. Cargo.lock is always included. When missing, a new lock file will be generated unless the --exclude-lockfile flag is used. cargo-install(1) will use the packaged lock file if the --locked flag is used. A .cargo_vcs_info.json file is included that contains information about the current VCS checkout hash if available, as well as a flag if the worktree is dirty. Symlinks are flattened to their target files. Files and directories are included or excluded based on rules mentioned in the [include] and [exclude] fields . Extract the .crate file and build it to verify it can build. This will rebuild your package from scratch to ensure that it can be built from a pristine state. The --no-verify flag can be used to skip this step. Check that build scripts did not modify any source files. The list of files included can be controlled with the include and exclude fields in the manifest. See the reference for more details about packaging and publishing. .cargo_vcs_info.json format Will generate a .cargo_vcs_info.json in the following format { "git": { "sha1": "aac20b6e7e543e6dd4118b246c77225e3a3a1302", "dirty": true }, "path_in_vcs": "" } dirty indicates that the Git worktree was dirty when the package was built. path_in_vcs will be set to a repo-relative path for packages in subdirectories of the version control repository. The compatibility of this file is maintained under the same policy as the JSON output of cargo-metadata(1) . Note that this file provides a best-effort snapshot of the VCS information. However, the provenance of the package is not verified. There is no guarantee that the source code in the tarball matches the VCS information. OPTIONS Package Options -l --list Print files included in a package without making one. --no-verify Don’t verify the contents by building them. --no-metadata Ignore warnings about a lack of human-usable metadata (such as the description or the license). --allow-dirty Allow working directories with uncommitted VCS changes to be packaged. --exclude-lockfile Don’t include the lock file when packaging. This flag is not for general use. Some tools may expect a lock file to be present (e.g. cargo install --locked ). Consider other options before using this. --index index The URL of the registry index to use. --registry registry Name of the registry to package for; see cargo publish --help for more details about configuration of registry names. The packages will not be published to this registry, but if we are packaging multiple inter-dependent crates, lock-files will be generated under the assumption that dependencies will be published to this registry. --message-format fmt Specifies the output message format. Currently, it only works with --list and affects the file listing format. This is unstable and requires -Zunstable-options . Valid output formats: human (default): Display in a file-per-line format. json : Emit machine-readable JSON information about each package. One package per JSON line (Newline delimited JSON). { /* The Package ID Spec of the package. */ "id": "path+file:///home/foo#0.0.0", /* Files of this package */ "files" { /* Relative path in the archive file. */ "Cargo.toml.orig": { /* Where the file is from. - "generate" for file being generated during packaging - "copy" for file being copied from another location. */ "kind": "copy", /* For the "copy" kind, it is an absolute path to the actual file content. For the "generate" kind, it is the original file the generated one is based on. */ "path": "/home/foo/Cargo.toml" }, "Cargo.toml": { "kind": "generate", "path": "/home/foo/Cargo.toml" }, "src/main.rs": { "kind": "copy", "path": "/home/foo/src/main.rs" } } } Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace ), and a non-virtual workspace will include only the root crate itself. -p spec … --package spec … Package only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Package all members in the workspace. --exclude SPEC … Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like * , ? and [] . However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Compilation Options --target triple Package for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi> . Possible values: Any supported target in rustc --print target-list . "host-tuple" , which will internally be substituted by the host’s target. This can be particularly useful if you’re cross-compiling some crates, and don’t want to specify your host’s machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts). A path to a custom target specification. See Custom Target Lookup Path for more information. This may also be specified with the build.target config value . Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache documentation for more details. --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value . Defaults to target in the root of the workspace. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation for more details. -F features --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --locked Asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of the following scenarios arises: The lock file is missing. Cargo attempted to change the lock file due to a different dependency resolution. It may be used in environments where deterministic builds are desired, such as in CI pipelines. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value . --frozen Equivalent to specifying both --locked and --offline . --lockfile-path PATH Changes the path of the lockfile from the default ( <workspace_root>/Cargo.lock ) to PATH . PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock ). Note that providing --lockfile-path will ignore existing lockfile at the default path, and instead will either use the lockfile from PATH , or write a new lockfile into the provided PATH if it doesn’t exist. This flag can be used to run most commands in read-only directories, writing lockfile into the provided PATH . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #14421 ). Miscellaneous Options -j N --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value . Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. If a string default is provided, it sets the value back to defaults. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. For example if the current package depends on dependencies fails and works , one of which fails to build, cargo package -j1 may or may not build the one that succeeds (depending on which one of the two builds Cargo picked to run first), whereas cargo package -j1 --keep-going would definitely run both builds, even if the one run first fails. Display Options -v --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value . -q --quiet Do not print cargo log messages. May also be specified with the term.quiet config value . --color when Control when colored output is used. Valid values: auto (default): Automatically detect if color support is available on the terminal. always : Always display colors. never : Never display colors. May also be specified with the term.color config value . Common Options + toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with + , it will be interpreted as a rustup toolchain name (such as +stable or +nightly ). See the rustup documentation for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE , or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest ( Cargo.toml ), as well as the directories searched for discovering .cargo/config.toml , for example. This option must appear before the command name, for example cargo -C path/to/my-project build . This option is only available on the nightly channel and requires the -Z unstable-options flag to enable (see #10098 ). -h --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. ENVIRONMENT See the reference for details on environment variables that Cargo reads. EXIT STATUS 0 : Cargo succeeded. 101 : Cargo failed to complete. EXAMPLES Create a compressed .crate file of the current package: cargo package SEE ALSO cargo(1) , cargo-publish(1) | 2026-01-13T09:29:13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.