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/cmp/trait.Ord.html | Ord in std::cmp - Rust This old browser is unsupported and will most likely display funky things. Ord std 1.92.0 (ded5c06cf 2025-12-08) Ord Sections Corollaries Derivable Lexicographical comparison How can I implement Ord ? Examples of incorrect Ord implementations Required Methods cmp Provided Methods clamp max min Dyn Compatibility Implementors In std:: cmp std :: cmp Trait Ord Copy item path 1.0.0 (const: unstable ) · Source pub trait Ord: Eq + PartialOrd { // Required method fn cmp (&self, other: &Self) -> Ordering ; // Provided methods fn max (self, other: Self) -> Self where Self: Sized { ... } fn min (self, other: Self) -> Self where Self: Sized { ... } fn clamp (self, min: Self, max: Self) -> Self where Self: Sized { ... } } Expand description Trait for types that form a total order . Implementations must be consistent with the PartialOrd implementation, and ensure max , min , and clamp are consistent with cmp : partial_cmp(a, b) == Some(cmp(a, b)) . max(a, b) == max_by(a, b, cmp) (ensured by the default implementation). min(a, b) == min_by(a, b, cmp) (ensured by the default implementation). For a.clamp(min, max) , see the method docs (ensured by the default implementation). Violating these requirements is a logic error. The behavior resulting from a logic error is not specified, but users of the trait must ensure that such logic errors do not result in undefined behavior. This means that unsafe code must not rely on the correctness of these methods. § Corollaries From the above and the requirements of PartialOrd , it follows that for all a , b and c : exactly one of a < b , a == b or a > b is true; and < is transitive: a < b and b < c implies a < c . The same must hold for both == and > . Mathematically speaking, the < operator defines a strict weak order . In cases where == conforms to mathematical equality, it also defines a strict total order . § Derivable This trait can be used with #[derive] . When derive d on structs, it will produce a lexicographic ordering based on the top-to-bottom declaration order of the struct’s members. When derive d on enums, variants are ordered primarily by their discriminants. Secondarily, they are ordered by their fields. By default, the discriminant is smallest for variants at the top, and largest for variants at the bottom. Here’s an example: #[derive(PartialEq, Eq, PartialOrd, Ord)] enum E { Top, Bottom, } assert! (E::Top < E::Bottom); However, manually setting the discriminants can override this default behavior: #[derive(PartialEq, Eq, PartialOrd, Ord)] enum E { Top = 2 , Bottom = 1 , } assert! (E::Bottom < E::Top); § Lexicographical comparison Lexicographical comparison is an operation with the following properties: Two sequences are compared element by element. The first mismatching element defines which sequence is lexicographically less or greater than the other. If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other. If two sequences have equivalent elements and are of the same length, then the sequences are lexicographically equal. An empty sequence is lexicographically less than any non-empty sequence. Two empty sequences are lexicographically equal. § How can I implement Ord ? Ord requires that the type also be PartialOrd , PartialEq , and Eq . Because Ord implies a stronger ordering relationship than PartialOrd , and both Ord and PartialOrd must agree, you must choose how to implement Ord first . You can choose to derive it, or implement it manually. If you derive it, you should derive all four traits. If you implement it manually, you should manually implement all four traits, based on the implementation of Ord . Here’s an example where you want to define the Character comparison by health and experience only, disregarding the field mana : use std::cmp::Ordering; struct Character { health: u32, experience: u32, mana: f32, } impl Ord for Character { fn cmp( & self , other: & Self ) -> Ordering { self .experience .cmp( & other.experience) .then( self .health.cmp( & other.health)) } } impl PartialOrd for Character { fn partial_cmp( & self , other: & Self ) -> Option <Ordering> { Some ( self .cmp(other)) } } impl PartialEq for Character { fn eq( & self , other: & Self ) -> bool { self .health == other.health && self .experience == other.experience } } impl Eq for Character {} If all you need is to slice::sort a type by a field value, it can be simpler to use slice::sort_by_key . § Examples of incorrect Ord implementations use std::cmp::Ordering; #[derive(Debug)] struct Character { health: f32, } impl Ord for Character { fn cmp( & self , other: & Self ) -> std::cmp::Ordering { if self .health < other.health { Ordering::Less } else if self .health > other.health { Ordering::Greater } else { Ordering::Equal } } } impl PartialOrd for Character { fn partial_cmp( & self , other: & Self ) -> Option <Ordering> { Some ( self .cmp(other)) } } impl PartialEq for Character { fn eq( & self , other: & Self ) -> bool { self .health == other.health } } impl Eq for Character {} let a = Character { health: 4.5 }; let b = Character { health: f32::NAN }; // Mistake: floating-point values do not form a total order and using the built-in comparison // operands to implement `Ord` irregardless of that reality does not change it. Use // `f32::total_cmp` if you need a total order for floating-point values. // Reflexivity requirement of `Ord` is not given. assert! (a == a); assert! (b != b); // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be // true, not both or neither. assert_eq! ((a < b) as u8 + (b < a) as u8, 0 ); use std::cmp::Ordering; #[derive(Debug)] struct Character { health: u32, experience: u32, } impl PartialOrd for Character { fn partial_cmp( & self , other: & Self ) -> Option <Ordering> { Some ( self .cmp(other)) } } impl Ord for Character { fn cmp( & self , other: & Self ) -> std::cmp::Ordering { if self .health < 50 { self .health.cmp( & other.health) } else { self .experience.cmp( & other.experience) } } } // For performance reasons implementing `PartialEq` this way is not the idiomatic way, but it // ensures consistent behavior between `PartialEq`, `PartialOrd` and `Ord` in this example. impl PartialEq for Character { fn eq( & self , other: & Self ) -> bool { self .cmp(other) == Ordering::Equal } } impl Eq for Character {} let a = Character { health: 3 , experience: 5 , }; let b = Character { health: 10 , experience: 77 , }; let c = Character { health: 143 , experience: 2 , }; // Mistake: The implementation of `Ord` compares different fields depending on the value of // `self.health`, the resulting order is not total. // Transitivity requirement of `Ord` is not given. If a is smaller than b and b is smaller than // c, by transitive property a must also be smaller than c. assert! (a < b && b < c && c < a); // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be // true, not both or neither. assert_eq! ((a < c) as u8 + (c < a) as u8, 2 ); The documentation of PartialOrd contains further examples, for example it’s wrong for PartialOrd and PartialEq to disagree. Required Methods § 1.0.0 · Source fn cmp (&self, other: &Self) -> Ordering This method returns an Ordering between self and other . By convention, self.cmp(&other) returns the ordering matching the expression self <operator> other if true. § Examples use std::cmp::Ordering; assert_eq! ( 5 .cmp( & 10 ), Ordering::Less); assert_eq! ( 10 .cmp( & 5 ), Ordering::Greater); assert_eq! ( 5 .cmp( & 5 ), Ordering::Equal); Provided Methods § 1.21.0 · Source fn max (self, other: Self) -> Self where Self: Sized , Compares and returns the maximum of two values. Returns the second argument if the comparison determines them to be equal. § Examples assert_eq! ( 1 .max( 2 ), 2 ); assert_eq! ( 2 .max( 2 ), 2 ); use std::cmp::Ordering; #[derive(Eq)] struct Equal( & 'static str); impl PartialEq for Equal { fn eq( & self , other: & Self ) -> bool { true } } impl PartialOrd for Equal { fn partial_cmp( & self , other: & Self ) -> Option <Ordering> { Some (Ordering::Equal) } } impl Ord for Equal { fn cmp( & self , other: & Self ) -> Ordering { Ordering::Equal } } assert_eq! (Equal( "self" ).max(Equal( "other" )). 0 , "other" ); 1.21.0 · Source fn min (self, other: Self) -> Self where Self: Sized , Compares and returns the minimum of two values. Returns the first argument if the comparison determines them to be equal. § Examples assert_eq! ( 1 .min( 2 ), 1 ); assert_eq! ( 2 .min( 2 ), 2 ); use std::cmp::Ordering; #[derive(Eq)] struct Equal( & 'static str); impl PartialEq for Equal { fn eq( & self , other: & Self ) -> bool { true } } impl PartialOrd for Equal { fn partial_cmp( & self , other: & Self ) -> Option <Ordering> { Some (Ordering::Equal) } } impl Ord for Equal { fn cmp( & self , other: & Self ) -> Ordering { Ordering::Equal } } assert_eq! (Equal( "self" ).min(Equal( "other" )). 0 , "self" ); 1.50.0 · Source fn clamp (self, min: Self, max: Self) -> Self where Self: Sized , Restrict a value to a certain interval. Returns max if self is greater than max , and min if self is less than min . Otherwise this returns self . § Panics Panics if min > max . § Examples assert_eq! ((- 3 ).clamp(- 2 , 1 ), - 2 ); assert_eq! ( 0 .clamp(- 2 , 1 ), 0 ); assert_eq! ( 2 .clamp(- 2 , 1 ), 1 ); Dyn Compatibility § This trait is not dyn compatible . In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe. Implementors § Source § impl Ord for AsciiChar 1.34.0 (const: unstable ) · Source § impl Ord for Infallible 1.0.0 · Source § impl Ord for ErrorKind 1.7.0 · Source § impl Ord for IpAddr 1.0.0 · Source § impl Ord for SocketAddr 1.0.0 (const: unstable ) · Source § impl Ord for Ordering 1.0.0 (const: unstable ) · Source § impl Ord for bool 1.0.0 (const: unstable ) · Source § impl Ord for char 1.0.0 (const: unstable ) · Source § impl Ord for i8 1.0.0 (const: unstable ) · Source § impl Ord for i16 1.0.0 (const: unstable ) · Source § impl Ord for i32 1.0.0 (const: unstable ) · Source § impl Ord for i64 1.0.0 (const: unstable ) · Source § impl Ord for i128 1.0.0 (const: unstable ) · Source § impl Ord for isize Source § impl Ord for ! 1.0.0 · Source § impl Ord for str Implements ordering of strings. Strings are ordered lexicographically by their byte values. This orders Unicode code points based on their positions in the code charts. This is not necessarily the same as “alphabetical” order, which varies by language and locale. Sorting strings according to culturally-accepted standards requires locale-specific data that is outside the scope of the str type. 1.0.0 (const: unstable ) · Source § impl Ord for u8 1.0.0 (const: unstable ) · Source § impl Ord for u16 1.0.0 (const: unstable ) · Source § impl Ord for u32 1.0.0 (const: unstable ) · Source § impl Ord for u64 1.0.0 (const: unstable ) · Source § impl Ord for u128 1.0.0 (const: unstable ) · Source § impl Ord for () 1.0.0 (const: unstable ) · Source § impl Ord for usize 1.27.0 · Source § impl Ord for CpuidResult 1.0.0 · Source § impl Ord for TypeId Source § impl Ord for ByteStr Source § impl Ord for ByteString 1.0.0 · Source § impl Ord for CStr 1.64.0 · Source § impl Ord for CString 1.0.0 · Source § impl Ord for OsStr 1.0.0 · Source § impl Ord for OsString 1.0.0 · Source § impl Ord for Error 1.33.0 · Source § impl Ord for PhantomPinned 1.0.0 · Source § impl Ord for Ipv4Addr 1.0.0 · Source § impl Ord for Ipv6Addr 1.0.0 · Source § impl Ord for SocketAddrV4 1.0.0 · Source § impl Ord for SocketAddrV6 1.10.0 · Source § impl Ord for Location <'_> 1.0.0 · Source § impl Ord for Components <'_> 1.0.0 · Source § impl Ord for Path 1.0.0 · Source § impl Ord for PathBuf 1.0.0 · Source § impl Ord for PrefixComponent <'_> Source § impl Ord for Alignment 1.0.0 · Source § impl Ord for String 1.3.0 · Source § impl Ord for Duration 1.8.0 · Source § impl Ord for Instant 1.8.0 · Source § impl Ord for SystemTime 1.0.0 · Source § impl<'a> Ord for Component <'a> 1.0.0 · Source § impl<'a> Ord for Prefix <'a> Source § impl<'a> Ord for PhantomContravariantLifetime <'a> Source § impl<'a> Ord for PhantomCovariantLifetime <'a> Source § impl<'a> Ord for PhantomInvariantLifetime <'a> 1.0.0 (const: unstable ) · Source § impl<A> Ord for &A where A: Ord + ? Sized , 1.0.0 (const: unstable ) · Source § impl<A> Ord for &mut A where A: Ord + ? Sized , 1.0.0 · Source § impl<B> Ord for Cow <'_, B> where B: Ord + ToOwned + ? Sized , Source § impl<Dyn> Ord for DynMetadata <Dyn> where Dyn: ? Sized , 1.4.0 · Source § impl<F> Ord for F where F: FnPtr , 1.0.0 · Source § impl<K, V, A> Ord for BTreeMap <K, V, A> where K: Ord , V: Ord , A: Allocator + Clone , 1.41.0 · Source § impl<Ptr> Ord for Pin <Ptr> where Ptr: Deref , <Ptr as Deref >:: Target : Ord , 1.0.0 (const: unstable ) · Source § impl<T> Ord for Option <T> where T: Ord , 1.36.0 · Source § impl<T> Ord for Poll <T> where T: Ord , 1.0.0 · Source § impl<T> Ord for *const T where T: ? Sized , Pointer comparison is by address, as produced by the [ <*const T>::addr ](pointer::addr) method. 1.0.0 · Source § impl<T> Ord for *mut T where T: ? Sized , Pointer comparison is by address, as produced by the <*mut T>::addr method. 1.0.0 · Source § impl<T> Ord for [T] where T: Ord , Implements comparison of slices lexicographically . 1.0.0 (const: unstable ) · Source § impl<T> Ord for (T₁, T₂, …, Tₙ) where T: Ord , This trait is implemented for tuples up to twelve items long. 1.10.0 · Source § impl<T> Ord for Cell <T> where T: Ord + Copy , 1.10.0 · Source § impl<T> Ord for RefCell <T> where T: Ord + ? Sized , Source § impl<T> Ord for PhantomContravariant <T> where T: ? Sized , Source § impl<T> Ord for PhantomCovariant <T> where T: ? Sized , 1.0.0 · Source § impl<T> Ord for PhantomData <T> where T: ? Sized , Source § impl<T> Ord for PhantomInvariant <T> where T: ? Sized , 1.20.0 · Source § impl<T> Ord for ManuallyDrop <T> where T: Ord + ? Sized , 1.28.0 (const: unstable ) · Source § impl<T> Ord for NonZero <T> where T: ZeroablePrimitive + Ord , 1.74.0 · Source § impl<T> Ord for Saturating <T> where T: Ord , 1.0.0 · Source § impl<T> Ord for Wrapping <T> where T: Ord , 1.25.0 · Source § impl<T> Ord for NonNull <T> where T: ? Sized , Source § impl<T> Ord for Exclusive <T> where T: Sync + Ord + ? Sized , 1.19.0 (const: unstable ) · Source § impl<T> Ord for Reverse <T> where T: Ord , 1.0.0 · Source § impl<T, A> Ord for Box <T, A> where T: Ord + ? Sized , A: Allocator , 1.0.0 · Source § impl<T, A> Ord for BTreeSet <T, A> where T: Ord , A: Allocator + Clone , 1.0.0 · Source § impl<T, A> Ord for LinkedList <T, A> where T: Ord , A: Allocator , 1.0.0 · Source § impl<T, A> Ord for VecDeque <T, A> where T: Ord , A: Allocator , 1.0.0 · Source § impl<T, A> Ord for Rc <T, A> where T: Ord + ? Sized , A: Allocator , Source § impl<T, A> Ord for UniqueRc <T, A> where T: Ord + ? Sized , A: Allocator , 1.0.0 · Source § impl<T, A> Ord for Arc <T, A> where T: Ord + ? Sized , A: Allocator , Source § impl<T, A> Ord for UniqueArc <T, A> where T: Ord + ? Sized , A: Allocator , 1.0.0 · Source § impl<T, A> Ord for Vec <T, A> where T: Ord , A: Allocator , Implements ordering of vectors, lexicographically . 1.0.0 (const: unstable ) · Source § impl<T, E> Ord for Result <T, E> where T: Ord , E: Ord , 1.0.0 · Source § impl<T, const N: usize > Ord for [T; N] where T: Ord , Implements comparison of arrays lexicographically . Source § impl<T, const N: usize > Ord for Simd <T, N> where LaneCount <N>: SupportedLaneCount , T: SimdElement + Ord , Lexicographic order. For the SIMD elementwise minimum and maximum, use simd_min and simd_max instead. Source § impl<Y, R> Ord for CoroutineState <Y, R> where Y: Ord , R: Ord , | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#cargo-package1 | 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#generic-readerwriter-functions-take-r-read-and-w-write-by-value-c-rw-value | 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---index | 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--l | 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.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 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 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%3DAT3JYaROIHDRnGnvxRuIozFF_BGGvvoNi8kVPWnSK0yCW2_Va2rKJWNXZ3PUqk5CKpNtOfbF-WNUpIWc7WVvePlsk9n9z3ptr24Okxk2028tZW0HuZ3QVvGoPKfc7Ts55I89ELD7U7OWf7bu | 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/cargo/commands/cargo-package.html#description | 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#buildrustc-workspace-wrapper | 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://fr-fr.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1ho_VP7aujGp5hB4ABLthmbsEWrryyldymj0vBdjJwyRf7zNOtfd1oG7waETjDOdLBwcZdBo3rgfTtglHDh6uX0PyAMCZgocf5nLGRtfjyQI5DR8xukPL7vIBSBrdeFJ7kQX0NDPsm3Epp | 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://zh-cn.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 选民信息中心 隐私政策 隐私中心 关于 创建广告 创建公共主页 开发者 招聘信息 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%3DAT01G6_nw6Bh-5sCbp2-aSr0g4Qn7kzux3KaClq4B-Ydqu_2cilx63HukRJNrpVSfO5KTOnvI2cAQAO9cOP5vcEy6U8cteIXFwQYm9A31sMi4P1LSY6nof6oJFyCIthvYsIp7MuPsMmVpsdU | 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://l.facebook.com/l.php?u=https%3A%2F%2Fwww.instagram.com%2F&h=AT2gGCyUfAUoOkfYXT_WEr-wxuIHOxcIrRZM0NOHBPRxnS_5Wqu1kPqTGMUMXWHVFr_xX1qNfW7FpadkxY_bgPkFrb_640SagZn4I9F0ewbSkKzn1VgcOJo46d2LgFoY4j7KR_AZC_64rwX5 | 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://ko-kr.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT0QX8FCxnPbaohRPPlkE8vieN29WhNqd6a40vSbtXnxh459bfCaZwjbfz9FMjMdHSCLgicWeGMsh4-MPZMnFDdK_kI2oKJU8dPDJOAhE-d4nnCOBHOM2xEWxIsUB0rq57x0y2EvdDML_Gk-5R6e_eKCTtzFQw | 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/std/convert/trait.TryInto.html | TryInto in std::convert - Rust This old browser is unsupported and will most likely display funky things. TryInto std 1.92.0 (ded5c06cf 2025-12-08) TryInto Sections Implementing TryInto Required Associated Types Error Required Methods try_into Dyn Compatibility Implementors In std:: convert std :: convert Trait TryInto Copy item path 1.34.0 (const: unstable ) · Source pub trait TryInto<T>: Sized { type Error ; // Required method fn try_into (self) -> Result <T, Self:: Error >; } Expand description An attempted conversion that consumes self , which may or may not be expensive. Library authors should usually not directly implement this trait, but should prefer implementing the TryFrom trait, which offers greater flexibility and provides an equivalent TryInto implementation for free, thanks to a blanket implementation in the standard library. For more information on this, see the documentation for Into . Prefer using TryInto over TryFrom when specifying trait bounds on a generic function to ensure that types that only implement TryInto can be used as well. § Implementing TryInto This suffers the same restrictions and reasoning as implementing Into , see there for details. Required Associated Types § 1.34.0 · Source type Error The type returned in the event of a conversion error. Required Methods § 1.34.0 · Source fn try_into (self) -> Result <T, Self:: Error > Performs the conversion. Dyn Compatibility § This trait is not dyn compatible . In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe. Implementors § 1.34.0 (const: unstable ) · Source § impl<T, U> TryInto <U> for T where U: TryFrom <T>, Source § type Error = <U as TryFrom <T>>:: Error | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-package.html#option-cargo-package--h | 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=AT0b-SavvqLYnhMwFBoblroC84Lko1DCu203gafA3uqPPkOxwzrb0c4vPUh-k-s7YBRpJUJ2usg25rShuzKt59eW4Jq_TrCWau6YO_xl6DNwokFJ98QHzN-Q8loyAK5MfGkYXVAuoXLpAOnA | 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#option-cargo-package---no-metadata | 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%3DAT1ho_VP7aujGp5hB4ABLthmbsEWrryyldymj0vBdjJwyRf7zNOtfd1oG7waETjDOdLBwcZdBo3rgfTtglHDh6uX0PyAMCZgocf5nLGRtfjyQI5DR8xukPL7vIBSBrdeFJ7kQX0NDPsm3Epp | 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://www.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT3JYaROIHDRnGnvxRuIozFF_BGGvvoNi8kVPWnSK0yCW2_Va2rKJWNXZ3PUqk5CKpNtOfbF-WNUpIWc7WVvePlsk9n9z3ptr24Okxk2028tZW0HuZ3QVvGoPKfc7Ts55I89ELD7U7OWf7bu | 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://rust-lang.github.io/api-guidelines/interoperability.html#collections-implement-fromiterator-and-extend-c-collect | 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#error-types-are-meaningful-and-well-behaved-c-good-err | 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---registry | 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/rfcs/0430-finalizing-naming-conventions.html#summary | 0430-finalizing-naming-conventions - The Rust RFC 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 Rust RFC Book Start Date: 2014-11-02 RFC PR: rust-lang/rfcs#430 Rust Issue: rust-lang/rust#19091 Summary This conventions RFC tweaks and finalizes a few long-running de facto conventions, including capitalization/underscores, and the role of the unwrap method. See this RFC for a competing proposal for unwrap . Motivation This is part of the ongoing conventions formalization process. The conventions described here have been loosely followed for a long time, but this RFC seeks to nail down a few final details and make them official. Detailed design General naming conventions In general, Rust tends to use UpperCamelCase for “type-level” constructs (types and traits) and snake_case for “value-level” constructs. More precisely, the proposed (and mostly followed) conventions are: Item Convention Crates snake_case (but prefer single word) Modules snake_case Types UpperCamelCase Traits UpperCamelCase Enum variants UpperCamelCase Functions snake_case Methods snake_case General constructors new or with_more_details Conversion constructors from_some_other_type Local variables snake_case Static variables SCREAMING_SNAKE_CASE Constant variables SCREAMING_SNAKE_CASE Type parameters concise UpperCamelCase , usually single uppercase letter: T Lifetimes short, lowercase: 'a Fine points In UpperCamelCase , acronyms count as one word: use Uuid rather than UUID . In snake_case , acronyms are lower-cased: is_xid_start . In UpperCamelCase names multiple numbers can be separated by a _ for clarity: Windows10_1709 instead of Windows101709 . In snake_case or SCREAMING_SNAKE_CASE , a “word” should never consist of a single letter unless it is the last “word”. So, we have btree_map rather than b_tree_map , but PI_2 rather than PI2 . unwrap , into_foo and into_inner There has been a long running debate about the name of the unwrap method found in Option and Result , but also a few other standard library types. Part of the problem is that for some types (e.g. BufferedReader ), unwrap will never panic; but for Option and Result calling unwrap is akin to asserting that the value is Some / Ok . There’s basic agreement that we should have an unambiguous term for the Option / Result version of unwrap . Proposals have included assert , ensure , expect , unwrap_or_panic and others; see the links above for extensive discussion. No clear consensus has emerged. This RFC proposes a simple way out: continue to call the methods unwrap for Option and Result , and rename other uses of unwrap to follow conversion conventions. Whenever possible, these panic-free unwrapping operations should be into_foo for some concrete foo , but for generic types like RefCell the name into_inner will suffice. By convention, these into_ methods cannot panic; and by (proposed) convention, unwrap should be reserved for an into_inner conversion that can . Drawbacks Not really applicable; we need to finalize these conventions. Unresolved questions Are there remaining subtleties about the rules here that should be clarified? | 2026-01-13T09:29:13 |
https://telegram.org/apps#apps-para-moviles | Telegram Applications English Bahasa Indonesia Bahasa Melayu Deutsch Español Français Italiano Nederlands O‘zbek Polski Português (Brasil) Türkçe Беларуская Русский Українська Қазақша العربية فارسی 한국어 Twitter Home FAQ Apps API Moderation Telegram Applications Telegram apps are open source and support reproducible builds . Anyone can independently verify that Telegram apps you download from App Store or Google Play were built using the exact same code that we publish. Mobile apps Telegram for Android Telegram for iPhone and iPad Desktop apps Telegram for Windows/Mac/Linux Telegram for macOS Web apps Telegram WebA Telegram WebK Telegram Database Library (TDLib) TDLib – a cross-platform client designed to facilitate creating custom apps on the Telegram platform. Telegram X for Android – a slick experimental Telegram client based on TDLib. Unofficial apps Unigram, a client optimized for Windows (based on TDLib ) Telegram CLI for Linux MadelineProto Source code This code allows security researchers to fully evaluate our end-to-end encryption implementation . It is also possible to independently verify that Telegram apps available on Google Play and App Store are built using the same code that we publish on GitHub. Telegram Database Library Cross-platform library for building custom Telegram apps, see TDLib for details. Licensed under Boost 1.0 . GitHub » Telegram for Android Official Android App, see Google Play Market page for full description. Licensed under GNU GPL v. 2 or later . GitHub » Download APK File » Telegram for iOS Licensed under GNU GPL v. 2 or later . GitHub » Telegram for macOS Native macOS client. Licensed under GNU GPL v. 2 . GitHub » Telegram for Web browsers Telegram Web, Version K . Mac, Windows, Linux, Mobile. Licensed under GNU GPL v. 3 . GitHub » Telegram Web, Version A . Mac, Windows, Linux, Mobile. Licensed under GNU GPL v. 3 . GitHub » Legacy JavaScript client . Mac, Windows, Linux. Licensed under GNU GPL v. 3 . GitHub » Telegram React JavaScript client for browsers. Mac, Windows, Linux. Licensed under GNU GPL v. 3 . GitHub » Telegram Desktop Qt-based desktop client. Mac, Windows, Linux. Licensed under GNU GPL v. 3 . GitHub » Telegram for WP Licensed under GNU GPL v. 2 or later . GitHub » Telegram X for Android Alternative Telegram client for Android based on TDLib. Licensed under GPL v.3.0 GitHub » Unofficial apps Telegram CLI (Unofficial) Linux Command-line interface for Telegram. Licensed under GNU GPL v. 2 . GitHub » Unigram (Unofficial) A Telegram client optimized for Windows. Licensed under GNU GPL v. 3 or later . GitHub » MadelineProto (Unofficial) A PHP MTProto Telegram client. Licensed under GNU AGPL v. 3 . GitHub » Bug Bounty Program Telegram welcomes developers and the security research community to audit its services, code and protocol seeking vulnerabilities or security-related issues. Learn more about our Bug Bounty Program here . Telegram Telegram is a cloud-based mobile and desktop messaging app with a focus on security and speed. About FAQ Privacy Press Mobile Apps iPhone/iPad Android Mobile Web Desktop Apps PC/Mac/Linux macOS Web-browser Platform API Translations Instant View About Blog Press Moderation | 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%3DAT1ho_VP7aujGp5hB4ABLthmbsEWrryyldymj0vBdjJwyRf7zNOtfd1oG7waETjDOdLBwcZdBo3rgfTtglHDh6uX0PyAMCZgocf5nLGRtfjyQI5DR8xukPL7vIBSBrdeFJ7kQX0NDPsm3Epp | 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://th-th.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT1ho_VP7aujGp5hB4ABLthmbsEWrryyldymj0vBdjJwyRf7zNOtfd1oG7waETjDOdLBwcZdBo3rgfTtglHDh6uX0PyAMCZgocf5nLGRtfjyQI5DR8xukPL7vIBSBrdeFJ7kQX0NDPsm3Epp | 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://pt-br.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT3JYaROIHDRnGnvxRuIozFF_BGGvvoNi8kVPWnSK0yCW2_Va2rKJWNXZ3PUqk5CKpNtOfbF-WNUpIWc7WVvePlsk9n9z3ptr24Okxk2028tZW0HuZ3QVvGoPKfc7Ts55I89ELD7U7OWf7bu | 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/core/prelude/v1/attr.test.html | test in core::prelude::v1 - Rust This old browser is unsupported and will most likely display funky things. test core 1.92.0 (ded5c06cf 2025-12-08) In core:: prelude:: v1 core :: prelude :: v1 Attribute Macro test Copy item path 1.38.0 · Source #[test] Expand description Attribute macro applied to a function to turn it into a unit test. See the reference for more info. | 2026-01-13T09:29:13 |
https://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b33-guideline-no-additional-text | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#examples-from-the-standard-library-1 | 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://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b3-substantive-text | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#data-structures-implement-serdes-serialize-deserialize-c-serde | 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://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b42-guideline | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 2026-01-13T09:29:13 |
https://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b31-purpose | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 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%3DAT01G6_nw6Bh-5sCbp2-aSr0g4Qn7kzux3KaClq4B-Ydqu_2cilx63HukRJNrpVSfO5KTOnvI2cAQAO9cOP5vcEy6U8cteIXFwQYm9A31sMi4P1LSY6nof6oJFyCIthvYsIp7MuPsMmVpsdU | 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---message-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://www.mkdocs.org/about/contributing/ | Contributing - 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 Contributing to MkDocs Reporting an Issue Trying out the Development Version Installing for Development Installing Hatch Running all checks Translating themes Submitting Pull Requests Code of Conduct Contributing to MkDocs An introduction to contributing to the MkDocs project. The MkDocs project welcomes contributions from developers and users in the open source community. Contributions can be made in a number of ways, a few examples are: Code patches via pull requests Documentation improvements Bug reports and patch reviews For information about available communication channels please refer to the README file in our GitHub repository. Reporting an Issue Please include as much detail as you can. Let us know your platform and MkDocs version. If the problem is visual (for example a theme or design issue), please add a screenshot. If you get an error, please include the full error message and traceback. It is particularly helpful if an issue report touches on all of these aspects: What are you trying to achieve? What is your mkdocs.yml configuration (+ other relevant files)? Preferably reduced to the minimal reproducible example. What did you expect to happen when applying this setup? What happened instead and how didn't it match your expectation? Trying out the Development Version If you want to just install and try out the latest development version of MkDocs (in case it already contains a fix for your issue), you can do so with the following command. This can be useful if you want to provide feedback for a new feature or want to confirm if a bug you have encountered is fixed in the git master. It is strongly recommended that you do this within a virtualenv . pip install git+https://github.com/mkdocs/mkdocs.git Installing for Development Note that for development you can just use Hatch directly as described below. If you wish to install a local clone of MkDocs anyway, you can run pip install --editable . . It is strongly recommended that you do this within a virtualenv . Installing Hatch The main tool that is used for development is Hatch . It manages dependencies (in a virtualenv that is created on the fly) and is also the command runner. So first, install it . Ideally in an isolated way with pipx install hatch (after [installing pipx ]), or just pip install hatch as a more well-known way. Running all checks To run all checks that are required for MkDocs, just run the following command in the cloned MkDocs repository: hatch run all This will encompass all of the checks mentioned below. All checks need to pass. Running tests To run the test suite for MkDocs, run the following commands: hatch run test:test hatch run integration:test It will attempt to run the tests against all of the Python versions we support. So don't be concerned if you are missing some. The rest will be verified by GitHub Actions when you submit a pull request. Python code style Python code within MkDocs' code base is formatted using Black and Isort and lint-checked using Ruff , all of which are configured in pyproject.toml . You can automatically check and format the code according to these tools with the following command: hatch run style:fix The code is also type-checked using mypy - also configured in pyproject.toml , it can be run like this: hatch run types:check Other style checks There are several other checks, such as spelling and JS style. To run all of them, use this command: hatch run lint:check Documentation of MkDocs itself After making edits to files under the docs/ dir, you can preview the site locally using the following command: hatch run docs:serve Note that any 'WARNING' should be resolved before submitting a contribution. Documentation files are also checked by markdownlint, so you should run this as well: hatch run lint:check If you add a new plugin to mkdocs.yml, you don't need to add it to any "requirements" file, because that is managed automatically. Info If you don't want to use Hatch, for documentation you can install requirements into a virtualenv, in one of these ways (with .venv being the virtualenv directory): .venv/bin/pip install -r requirements/requirements-docs.txt # Exact versions of dependencies. .venv/bin/pip install -r $(mkdocs get-deps) # Latest versions of all dependencies. Translating themes To localize a theme to your favorite language, follow the guide on Translating Themes . We welcome translation pull requests! Submitting Pull Requests If you're considering a large code contribution to MkDocs, please prefer to open an issue first to get early feedback on the idea. Once you think the code is ready to be reviewed, push it to your fork and send a pull request. For a change to be accepted it will most likely need to have tests and documentation if it is a new feature. When working with a pull request branch: Unless otherwise agreed, prefer commit over amend , and merge over rebase . Avoid force-pushes, otherwise review history is much harder to navigate. For the end result, the "unclean" history is fine because most pull requests are squash-merged on GitHub. Do not add to release-notes.md , this will be written later. Submitting changes to the builtin themes When installed with i18n support ( pip install 'mkdocs[i18n]' ), MkDocs allows themes to support being translated into various languages (referred to as locales) if they respect Jinja's i18n extension by wrapping text placeholders with {% trans %} and {% endtrans %} tags. Each time a translatable text placeholder is added, removed or changed in a theme template, the theme's Portable Object Template ( pot ) file needs to be updated by running the extract_messages command. To update the pot file for both built-in themes, run these commands: pybabel extract --project=MkDocs --copyright-holder=MkDocs --msgid-bugs-address='https://github.com/mkdocs/mkdocs/issues' --no-wrap --version="$(hatch version)" --mapping-file mkdocs/themes/babel.cfg --output-file mkdocs/themes/mkdocs/messages.pot mkdocs/themes/mkdocs pybabel extract --project=MkDocs --copyright-holder=MkDocs --msgid-bugs-address='https://github.com/mkdocs/mkdocs/issues' --no-wrap --version="$(hatch version)" --mapping-file mkdocs/themes/babel.cfg --output-file mkdocs/themes/readthedocs/messages.pot mkdocs/themes/readthedocs The updated pot file should be included in a PR with the updated template. The updated pot file will allow translation contributors to propose the translations needed for their preferred language. See the guide on Translating Themes for details. Note Contributors are not expected to provide translations with their changes to a theme's templates. However, they are expected to include an updated pot file so that everything is ready for translators to do their job. Code of Conduct Everyone interacting in the MkDocs project's codebases, issue trackers, chat rooms, and mailing lists is expected to follow the PyPA Code of Conduct . 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://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b21-purpose | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#interoperability | 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://docs.rs | Docs.rs Docs.rs docs.rs About docs.rs Badges Builds Metadata Shorthand URLs Download Rustdoc JSON Build queue Privacy policy Rust Rust website The Book Standard Library API Reference Rust by Example The Cargo Guide Clippy Documentation Docs.rs Search I'm Feeling Lucky Recent Releases bench-runner-0.1.0 Lightweight benchmarking harness for mobile devices 56 seconds ago xrange-0.1.2 Efficient range overlap detection and search / 高效范围重叠检测与搜索 one minute ago rand_core-0.9.5 Core random number generator traits and tools for implementation. one minute ago mobench-macros-0.1.0 Proc macros for bench-sdk - #[benchmark] attribute 2 minutes ago wl-proxy-0.1.0 Wayland connection proxy 2 minutes ago fallibles-0.1.1 Failure injection library for testing error handling in Rust 2 minutes ago fallibles-macro-0.1.1 Failure injection library for testing error handling in Rust 3 minutes ago fallibles-core-0.1.1 Failure injection library for testing error handling in Rust 3 minutes ago slsqp-rssl-0.1.0 slsqp rust impl, ported from scipy Fortran impl 3 minutes ago rspack-0.7.2 rspack 3 minutes ago skilo-0.2.0 CLI tool for Agent Skills development 8 minutes ago tycho-ethereum-0.129.0 Ethereum specific implementation of core tycho traits 9 minutes ago tycho-client-0.129.0 A library and CLI tool for querying and accessing liquidity data from Tycho indexer. 10 minutes ago tiff-0.11.1 TIFF decoding and encoding library in pure Rust 11 minutes ago vespertide-0.1.27 Rust workspace for defining database schemas in JSON and generating migration plans and SQL from model diffs 11 minutes ago | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/reference/config.html#credentials | 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/std/iter/trait.Extend.html | Extend in std::iter - Rust This old browser is unsupported and will most likely display funky things. Extend std 1.92.0 (ded5c06cf 2025-12-08) Extend Sections Examples Required Methods extend Provided Methods extend_one extend_reserve Dyn Compatibility Implementors In std:: iter std :: iter Trait Extend Copy item path 1.0.0 · Source pub trait Extend<A> { // Required method fn extend <T>(&mut self, iter: T) where T: IntoIterator <Item = A> ; // Provided methods fn extend_one (&mut self, item: A) { ... } fn extend_reserve (&mut self, additional: usize ) { ... } } Expand description Extend a collection with the contents of an iterator. Iterators produce a series of values, and collections can also be thought of as a series of values. The Extend trait bridges this gap, allowing you to extend a collection by including the contents of that iterator. When extending a collection with an already existing key, that entry is updated or, in the case of collections that permit multiple entries with equal keys, that entry is inserted. § Examples Basic usage: // You can extend a String with some chars: let mut message = String::from( "The first three letters are: " ); message.extend( & [ 'a' , 'b' , 'c' ]); assert_eq! ( "abc" , & message[ 29 .. 32 ]); Implementing Extend : // A sample collection, that's just a wrapper over Vec<T> #[derive(Debug)] struct MyCollection(Vec<i32>); // Let's give it some methods so we can create one and add things // to it. impl MyCollection { fn new() -> MyCollection { MyCollection(Vec::new()) } fn add( &mut self , elem: i32) { self . 0 .push(elem); } } // since MyCollection has a list of i32s, we implement Extend for i32 impl Extend<i32> for MyCollection { // This is a bit simpler with the concrete type signature: we can call // extend on anything which can be turned into an Iterator which gives // us i32s. Because we need i32s to put into MyCollection. fn extend<T: IntoIterator<Item=i32>>( &mut self , iter: T) { // The implementation is very straightforward: loop through the // iterator, and add() each element to ourselves. for elem in iter { self .add(elem); } } } let mut c = MyCollection::new(); c.add( 5 ); c.add( 6 ); c.add( 7 ); // let's extend our collection with three more numbers c.extend( vec! [ 1 , 2 , 3 ]); // we've added these elements onto the end assert_eq! ( "MyCollection([5, 6, 7, 1, 2, 3])" , format! ( "{c:?}" )); Required Methods § 1.0.0 · Source fn extend <T>(&mut self, iter: T) where T: IntoIterator <Item = A>, Extends a collection with the contents of an iterator. As this is the only required method for this trait, the trait-level docs contain more details. § Examples // You can extend a String with some chars: let mut message = String::from( "abc" ); message.extend([ 'd' , 'e' , 'f' ].iter()); assert_eq! ( "abcdef" , & message); Provided Methods § Source fn extend_one (&mut self, item: A) 🔬 This is a nightly-only experimental API. ( extend_one #72631 ) Extends a collection with exactly one element. Source fn extend_reserve (&mut self, additional: usize ) 🔬 This is a nightly-only experimental API. ( extend_one #72631 ) Reserves capacity in a collection for the given number of additional elements. The default implementation does nothing. Dyn Compatibility § This trait is not dyn compatible . In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe. Implementors § Source § impl Extend < AsciiChar > for String 1.0.0 · Source § impl Extend < char > for String 1.28.0 · Source § impl Extend < () > for () 1.52.0 · Source § impl Extend < OsString > for OsString 1.4.0 · Source § impl Extend < String > for String Source § impl<'a> Extend <&'a AsciiChar > for String 1.2.0 · Source § impl<'a> Extend <&'a char > for String 1.0.0 · Source § impl<'a> Extend <&'a str > for String 1.52.0 · Source § impl<'a> Extend <&'a OsStr > for OsString 1.19.0 · Source § impl<'a> Extend < Cow <'a, str >> for String 1.52.0 · Source § impl<'a> Extend < Cow <'a, OsStr >> for OsString 1.2.0 · Source § impl<'a, K, V, A> Extend <( &'a K , &'a V )> for BTreeMap <K, V, A> where K: Ord + Copy , V: Copy , A: Allocator + Clone , 1.4.0 · Source § impl<'a, K, V, S> Extend <( &'a K , &'a V )> for HashMap <K, V, S> where K: Eq + Hash + Copy , V: Copy , S: BuildHasher , 1.2.0 · Source § impl<'a, T, A> Extend < &'a T > for BTreeSet <T, A> where T: 'a + Ord + Copy , A: Allocator + Clone , 1.2.0 · Source § impl<'a, T, A> Extend < &'a T > for BinaryHeap <T, A> where T: 'a + Ord + Copy , A: Allocator , 1.2.0 · Source § impl<'a, T, A> Extend < &'a T > for LinkedList <T, A> where T: 'a + Copy , A: Allocator , 1.2.0 · Source § impl<'a, T, A> Extend < &'a T > for VecDeque <T, A> where T: 'a + Copy , A: Allocator , 1.2.0 · Source § impl<'a, T, A> Extend < &'a T > for Vec <T, A> where T: Copy + 'a, A: Allocator , Extend implementation that copies elements out of references before pushing them onto the Vec. This implementation is specialized for slice iterators, where it uses copy_from_slice to append the entire slice at once. 1.4.0 · Source § impl<'a, T, S> Extend < &'a T > for HashSet <T, S> where T: 'a + Eq + Hash + Copy , S: BuildHasher , 1.45.0 · Source § impl<A> Extend < Box < str , A>> for String where A: Allocator , 1.0.0 · Source § impl<K, V, A> Extend < (K, V) > for BTreeMap <K, V, A> where K: Ord , A: Allocator + Clone , 1.0.0 · Source § impl<K, V, S> Extend < (K, V) > for HashMap <K, V, S> where K: Eq + Hash , S: BuildHasher , Inserts all new key-values from the iterator and replaces values with existing keys with new values returned from the iterator. 1.0.0 · Source § impl<P: AsRef < Path >> Extend <P> for PathBuf 1.0.0 · Source § impl<T, A> Extend <T> for BTreeSet <T, A> where T: Ord , A: Allocator + Clone , 1.0.0 · Source § impl<T, A> Extend <T> for BinaryHeap <T, A> where T: Ord , A: Allocator , 1.0.0 · Source § impl<T, A> Extend <T> for LinkedList <T, A> where A: Allocator , 1.0.0 · Source § impl<T, A> Extend <T> for VecDeque <T, A> where A: Allocator , 1.0.0 · Source § impl<T, A> Extend <T> for Vec <T, A> where A: Allocator , 1.56.0 · Source § impl<T, ExtendT> Extend < (T₁, T₂, …, Tₙ) > for (ExtendT₁, ExtendT₂, …, ExtendTₙ) where ExtendT: Extend <T>, This trait is implemented for tuples up to twelve items long. The impl s for 1- and 3- through 12-ary tuples were stabilized after 2-tuples, in 1.85.0. 1.0.0 · Source § impl<T, S> Extend <T> for HashSet <T, S> where T: Eq + Hash , S: BuildHasher , | 2026-01-13T09:29:13 |
https://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b5-capitalization | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 2026-01-13T09:29:13 |
https://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b4-whitespace | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 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%3DAT01G6_nw6Bh-5sCbp2-aSr0g4Qn7kzux3KaClq4B-Ydqu_2cilx63HukRJNrpVSfO5KTOnvI2cAQAO9cOP5vcEy6U8cteIXFwQYm9A31sMi4P1LSY6nof6oJFyCIthvYsIp7MuPsMmVpsdU | 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.mkdocs.org/dev-guide/api/ | API Reference - 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 API reference Files File Config TemplateContext LiveReloadServer API reference Note The main entry point to the API is through Events that are received by plugins. These events' descriptions link back to this page. mkdocs.structure.files.Files A collection of File objects. src_paths: dict[str, File] property Soft-deprecated, prefer src_uris . src_uris: Mapping[str, File] property A mapping containing every file, with the keys being their src_uri . __iter__() -> Iterator[File] Iterate over the files within. __len__() -> int The number of files within. __contains__(path: str) -> bool Soft-deprecated, prefer get_file_from_path(path) is not None . get_file_from_path(path: str) -> File | None Return a File instance with File.src_uri equal to path. append(file: File) -> None Add file to the Files collection. remove(file: File) -> None Remove file from Files collection. copy_static_files(dirty: bool = False, *, inclusion: Callable[[InclusionLevel], bool] = InclusionLevel.is_included) -> None Copy static files from source to destination. documentation_pages(*, inclusion: Callable[[InclusionLevel], bool] = InclusionLevel.is_included) -> Sequence[File] Return iterable of all Markdown page file objects. static_pages() -> Sequence[File] Return iterable of all static page file objects. media_files() -> Sequence[File] Return iterable of all file objects which are not documentation or static pages. javascript_files() -> Sequence[File] Return iterable of all javascript file objects. css_files() -> Sequence[File] Return iterable of all CSS file objects. add_files_from_theme(env: jinja2.Environment, config: MkDocsConfig) -> None Retrieve static files from Jinja environment and add to collection. mkdocs.structure.files.File A MkDocs File object. It represents how the contents of one file should be populated in the destination site. A file always has its abs_dest_path (obtained by joining dest_dir and dest_path ), where the dest_dir is understood to be the site directory. content_bytes / content_string (new in MkDocs 1.6) can always be used to obtain the file's content. But it may be backed by one of the two sources: A physical source file at abs_src_path (by default obtained by joining src_dir and src_uri ). src_dir is understood to be the docs directory. Then content_bytes / content_string will read the file at abs_src_path . src_dir should be populated for real files and should be None for generated files. Since MkDocs 1.6 a file may alternatively be stored in memory - content_string / content_bytes . Then src_dir and abs_src_path will remain None . content_bytes / content_string need to be written to, or populated through the content argument in the constructor. But src_uri is still populated for such files as well! The virtual file pretends as if it originated from that path in the docs directory, and other values are derived. For static files the file is just copied to the destination, and dest_uri equals src_uri . For Markdown files (determined by the file extension in src_uri ) the destination content will be the rendered content, and dest_uri will have the .html extension and some additional transformations to the path, based on use_directory_urls . src_uri: str instance-attribute The pure path (always '/'-separated) of the source file relative to the source directory. generated_by: str | None = None class-attribute instance-attribute If not None, indicates that a plugin generated this file on the fly. The value is the plugin's entrypoint name and can be used to find the plugin by key in the PluginCollection. dest_path: str property writable Same as dest_uri (and synchronized with it) but will use backslashes on Windows. Discouraged. src_path: str = path instance-attribute property writable Same as src_uri (and synchronized with it) but will use backslashes on Windows. Discouraged. src_dir: str | None = src_dir instance-attribute The OS path of the top-level directory that the source file originates from. Assumed to be the docs_dir ; not populated for generated files. dest_dir: str = dest_dir instance-attribute The OS path of the destination directory (top-level site_dir) that the file should be copied to. use_directory_urls: bool = use_directory_urls instance-attribute Whether directory URLs ('foo/') should be used or not ('foo.html'). If False , a Markdown file is mapped to an HTML file of the same name (the file extension is changed to .html ). If True, a Markdown file is mapped to an HTML index file ( index.html ) nested in a directory using the "name" of the file in path . Non-Markdown files retain their original path. inclusion: InclusionLevel = inclusion class-attribute instance-attribute Whether the file will be excluded from the built site. name = cached_property(_get_stem) class-attribute instance-attribute Return the name of the file without its extension. dest_uri = cached_property(_get_dest_path) class-attribute instance-attribute The pure path (always '/'-separated) of the destination file relative to the destination directory. url = cached_property(_get_url) class-attribute instance-attribute The URI of the destination file relative to the destination directory as a string. abs_src_path: str | None cached property The absolute concrete path of the source file. Will use backslashes on Windows. Note: do not use this path to read the file, prefer content_bytes / content_string . abs_dest_path: str cached property The absolute concrete path of the destination file. Will use backslashes on Windows. content_bytes: bytes property writable Get the content of this file as a bytestring. May raise if backed by a real file ( abs_src_path ) if it cannot be read. If used as a setter, it defines the content of the file, and abs_src_path becomes unset. content_string: str property writable Get the content of this file as a string. Assumes UTF-8 encoding, may raise. May also raise if backed by a real file ( abs_src_path ) if it cannot be read. If used as a setter, it defines the content of the file, and abs_src_path becomes unset. generated(config: MkDocsConfig, src_uri: str, *, content: str | bytes | None = None, abs_src_path: str | None = None, inclusion: InclusionLevel = InclusionLevel.UNDEFINED) -> File classmethod Create a virtual file, backed either by in-memory content or by a file at abs_src_path . It will pretend to be a file in the docs dir at src_uri . edit_uri() -> str | None A path relative to the source repository to use for the "edit" button. Defaults to src_uri and can be overwritten. For generated files this should be set to None . url_relative_to(other: File | str) -> str Return url for file relative to other file. copy_file(dirty: bool = False) -> None Copy source file to destination, ensuring parent directories exist. is_documentation_page() -> bool Return True if file is a Markdown page. is_static_page() -> bool Return True if file is a static page (HTML, XML, JSON). is_media_file() -> bool Return True if file is not a documentation or static page. is_javascript() -> bool Return True if file is a JavaScript file. is_css() -> bool Return True if file is a CSS file. mkdocs.config.base.Config Bases: UserDict Base class for MkDocs configuration, plugin configuration (and sub-configuration) objects. It should be subclassed and have ConfigOption s defined as attributes. For examples, see mkdocs/contrib/search/ init .py and mkdocs/config/defaults.py. Behavior as it was prior to MkDocs 1.4 is now handled by LegacyConfig. __new__(*args, **kwargs) -> Config Compatibility: allow referring to LegacyConfig(...) constructor as Config(...) . set_defaults() -> None Set the base config by going through each validator and getting the default if it has one. load_dict(patch: dict) -> None Load config options from a dictionary. load_file(config_file: IO) -> None Load config options from the open file descriptor of a YAML file. mkdocs.utils.templates.TemplateContext Bases: TypedDict nav: Navigation instance-attribute pages: Sequence[File] instance-attribute base_url: str instance-attribute extra_css: Sequence[str] instance-attribute extra_javascript: Sequence[str] instance-attribute mkdocs_version: str instance-attribute build_date_utc: datetime.datetime instance-attribute config: MkDocsConfig instance-attribute page: Page | None instance-attribute mkdocs.livereload.LiveReloadServer Bases: ThreadingMixIn , WSGIServer watch(path: str, func: None = None, *, recursive: bool = True) -> None Add the 'path' to watched paths, call the function and reload when any file changes under it. unwatch(path: str) -> None Stop watching file changes for path. Raises if there was no corresponding watch call. 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://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b41-purpose | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 2026-01-13T09:29:13 |
https://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b32-guideline-verbatim-text | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/interoperability.html#types-are-send-and-sync-where-possible-c-send-sync | 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-lockfile | 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://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b2-how-these-guidelines-are-applied | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/std/marker/trait.Send.html | Send in std::marker - Rust This old browser is unsupported and will most likely display funky things. Send std 1.92.0 (ded5c06cf 2025-12-08) Send Implementors Auto Implementors In std:: marker std :: marker Trait Send Copy item path 1.0.0 · Source pub unsafe auto trait Send { } Expand description Types that can be transferred across thread boundaries. This trait is automatically implemented when the compiler determines it’s appropriate. An example of a non- Send type is the reference-counting pointer rc::Rc . If two threads attempt to clone Rc s that point to the same reference-counted value, they might try to update the reference count at the same time, which is undefined behavior because Rc doesn’t use atomic operations. Its cousin sync::Arc does use atomic operations (incurring some overhead) and thus is Send . See the Nomicon and the Sync trait for more details. Implementors § 1.26.0 · Source § impl ! Send for Args 1.26.0 · Source § impl ! Send for ArgsOs 1.0.0 · Source § impl ! Send for Arguments <'_> Source § impl ! Send for LocalWaker Source § impl Send for core::ffi::c_str:: Bytes <'_> 1.0.0 · Source § impl Send for TypeId 1.63.0 · Source § impl Send for BorrowedHandle <'_> Available on Windows only. 1.63.0 · Source § impl Send for HandleOrInvalid Available on Windows only. 1.63.0 · Source § impl Send for HandleOrNull Available on Windows only. 1.63.0 · Source § impl Send for OwnedHandle Available on Windows only. 1.10.0 · Source § impl Send for Location <'_> 1.6.0 · Source § impl Send for std::string:: Drain <'_> 1.36.0 · Source § impl Send for Waker 1.44.0 · Source § impl<'a> Send for IoSlice <'a> 1.44.0 · Source § impl<'a> Send for IoSliceMut <'a> Source § impl<Dyn> Send for DynMetadata <Dyn> where Dyn: ? Sized , 1.0.0 · Source § impl<T> ! Send for *const T where T: ? Sized , 1.0.0 · Source § impl<T> ! Send for *mut T where T: ? Sized , 1.25.0 · Source § impl<T> ! Send for NonNull <T> where T: ? Sized , NonNull pointers are not Send because the data they reference may be aliased. 1.0.0 · Source § impl<T> Send for &T where T: Sync + ? Sized , Source § impl<T> Send for ThinBox <T> where T: Send + ? Sized , ThinBox<T> is Send if T is Send because the data is owned. 1.0.0 · Source § impl<T> Send for Cell <T> where T: Send + ? Sized , 1.0.0 · Source § impl<T> Send for RefCell <T> where T: Send + ? Sized , 1.0.0 · Source § impl<T> Send for std::collections::linked_list:: Iter <'_, T> where T: Sync , 1.0.0 · Source § impl<T> Send for std::collections::linked_list:: IterMut <'_, T> where T: Send , 1.28.0 · Source § impl<T> Send for NonZero <T> where T: ZeroablePrimitive + Send , 1.31.0 · Source § impl<T> Send for ChunksExactMut <'_, T> where T: Send , 1.0.0 · Source § impl<T> Send for ChunksMut <'_, T> where T: Send , 1.0.0 · Source § impl<T> Send for std::slice:: Iter <'_, T> where T: Sync , 1.0.0 · Source § impl<T> Send for std::slice:: IterMut <'_, T> where T: Send , 1.31.0 · Source § impl<T> Send for RChunksExactMut <'_, T> where T: Send , 1.31.0 · Source § impl<T> Send for RChunksMut <'_, T> where T: Send , 1.0.0 · Source § impl<T> Send for AtomicPtr <T> 1.29.0 · Source § impl<T> Send for JoinHandle <T> 1.0.0 · Source § impl<T, A> ! Send for Rc <T, A> where A: Allocator , T: ? Sized , Source § impl<T, A> ! Send for UniqueRc <T, A> where A: Allocator , T: ? Sized , 1.4.0 · Source § impl<T, A> ! Send for std::rc:: Weak <T, A> where A: Allocator , T: ? Sized , Source § impl<T, A> Send for std::collections::linked_list:: Cursor <'_, T, A> where T: Sync , A: Allocator + Sync , Source § impl<T, A> Send for std::collections::linked_list:: CursorMut <'_, T, A> where T: Send , A: Allocator + Send , 1.0.0 · Source § impl<T, A> Send for LinkedList <T, A> where T: Send , A: Allocator + Send , 1.6.0 · Source § impl<T, A> Send for std::collections::vec_deque:: Drain <'_, T, A> where T: Send , A: Allocator + Send , 1.0.0 · Source § impl<T, A> Send for Arc <T, A> where T: Sync + Send + ? Sized , A: Allocator + Send , Source § impl<T, A> Send for UniqueArc <T, A> where T: Sync + Send + ? Sized , A: Allocator + Send , 1.4.0 · Source § impl<T, A> Send for std::sync:: Weak <T, A> where T: Sync + Send + ? Sized , A: Allocator + Send , 1.6.0 · Source § impl<T, A> Send for std::vec:: Drain <'_, T, A> where T: Send , A: Send + Allocator , 1.0.0 · Source § impl<T, A> Send for std::vec:: IntoIter <T, A> where T: Send , A: Allocator + Send , Source § impl<T: Send + ? Sized > Send for ReentrantLock <T> Source § impl<T: Send > Send for std::sync::mpmc:: Receiver <T> Source § impl<T: Send > Send for std::sync::mpmc:: Sender <T> 1.0.0 · Source § impl<T: Send > Send for std::sync::mpsc:: Receiver <T> 1.0.0 · Source § impl<T: Send > Send for std::sync::mpsc:: Sender <T> 1.0.0 · Source § impl<T: Send > Send for SyncSender <T> 1.70.0 · Source § impl<T: Send > Send for OnceLock <T> Source § impl<T: ? Sized + Send > Send for std::sync::nonpoison:: Mutex <T> T must be Send for a Mutex to be Send because it is possible to acquire the owned T from the Mutex via into_inner . Source § impl<T: ? Sized + Send > Send for std::sync::nonpoison:: RwLock <T> 1.0.0 · Source § impl<T: ? Sized + Send > Send for std::sync:: Mutex <T> T must be Send for a Mutex to be Send because it is possible to acquire the owned T from the Mutex via into_inner . 1.0.0 · Source § impl<T: ? Sized + Send > Send for std::sync:: RwLock <T> Source § impl<T: ? Sized > ! Send for std::sync::nonpoison:: MappedMutexGuard <'_, T> Source § impl<T: ? Sized > ! Send for std::sync::nonpoison:: MappedRwLockReadGuard <'_, T> Source § impl<T: ? Sized > ! Send for std::sync::nonpoison:: MappedRwLockWriteGuard <'_, T> Source § impl<T: ? Sized > ! Send for std::sync::nonpoison:: MutexGuard <'_, T> A MutexGuard is not Send to maximize platform portability. On platforms that use POSIX threads (commonly referred to as pthreads) there is a requirement to release mutex locks on the same thread they were acquired. For this reason, MutexGuard must not implement Send to prevent it being dropped from another thread. Source § impl<T: ? Sized > ! Send for std::sync::nonpoison:: RwLockReadGuard <'_, T> Source § impl<T: ? Sized > ! Send for std::sync::nonpoison:: RwLockWriteGuard <'_, T> Source § impl<T: ? Sized > ! Send for std::sync:: MappedMutexGuard <'_, T> Source § impl<T: ? Sized > ! Send for std::sync:: MappedRwLockReadGuard <'_, T> Source § impl<T: ? Sized > ! Send for std::sync:: MappedRwLockWriteGuard <'_, T> 1.0.0 · Source § impl<T: ? Sized > ! Send for std::sync:: MutexGuard <'_, T> A MutexGuard is not Send to maximize platform portability. On platforms that use POSIX threads (commonly referred to as pthreads) there is a requirement to release mutex locks on the same thread they were acquired. For this reason, MutexGuard must not implement Send to prevent it being dropped from another thread. Source § impl<T: ? Sized > ! Send for ReentrantLockGuard <'_, T> 1.0.0 · Source § impl<T: ? Sized > ! Send for std::sync:: RwLockReadGuard <'_, T> 1.0.0 · Source § impl<T: ? Sized > ! Send for std::sync:: RwLockWriteGuard <'_, T> Auto implementors § § impl ! Send for Vars § impl ! Send for VarsOs § impl ! Send for RawWaker § impl Send for AsciiChar § impl Send for BacktraceStatus § impl Send for std::cmp:: Ordering § impl Send for TryReserveErrorKind § impl Send for Infallible § impl Send for VarError § impl Send for FromBytesWithNulError § impl Send for c_void § impl Send for std::fmt:: Alignment § impl Send for DebugAsHex § impl Send for Sign § impl Send for std::fs:: TryLockError § impl Send for AtomicOrdering § impl Send for BasicBlock § impl Send for UnwindTerminateReason § impl Send for ErrorKind § impl Send for SeekFrom § impl Send for IpAddr § impl Send for Ipv6MulticastScope § impl Send for Shutdown § impl Send for std::net:: SocketAddr § impl Send for FpCategory § impl Send for IntErrorKind § impl Send for OneSidedRangeBound § impl Send for AncillaryError § impl Send for BacktraceStyle § impl Send for GetDisjointMutError § impl Send for SearchStep § impl Send for std::sync::atomic:: Ordering § impl Send for RecvTimeoutError § impl Send for TryRecvError § impl Send for bool § impl Send for char § impl Send for f16 § impl Send for f32 § impl Send for f64 § impl Send for f128 § impl Send for i8 § impl Send for i16 § impl Send for i32 § impl Send for i64 § impl Send for i128 § impl Send for isize § impl Send for ! § impl Send for str § impl Send for u8 § impl Send for u16 § impl Send for u32 § impl Send for u64 § impl Send for u128 § impl Send for () § impl Send for usize § impl Send for AllocError § impl Send for Global § impl Send for Layout § impl Send for LayoutError § impl Send for System § impl Send for TryFromSliceError § impl Send for std::ascii:: EscapeDefault § impl Send for Backtrace § impl Send for BacktraceFrame § impl Send for ByteStr § impl Send for ByteString § impl Send for BorrowError § impl Send for BorrowMutError § impl Send for CharTryFromError § impl Send for DecodeUtf16Error § impl Send for std::char:: EscapeDebug § impl Send for std::char:: EscapeDefault § impl Send for std::char:: EscapeUnicode § impl Send for ParseCharError § impl Send for ToLowercase § impl Send for ToUppercase § impl Send for TryFromCharError § impl Send for UnorderedKeyError § impl Send for TryReserveError § impl Send for JoinPathsError § impl Send for CStr § impl Send for CString § impl Send for FromBytesUntilNulError § impl Send for FromVecWithNulError § impl Send for IntoStringError § impl Send for NulError § impl Send for OsStr § impl Send for OsString § impl Send for std::fmt:: Error § impl Send for FormattingOptions § impl Send for DirBuilder § impl Send for DirEntry § impl Send for File § impl Send for FileTimes § impl Send for FileType § impl Send for Metadata § impl Send for OpenOptions § impl Send for Permissions § impl Send for ReadDir § impl Send for DefaultHasher § impl Send for RandomState § impl Send for SipHasher § impl Send for ReturnToArg § impl Send for UnwindActionArg § impl Send for std::io:: Empty § impl Send for std::io:: Error § impl Send for PipeReader § impl Send for PipeWriter § impl Send for std::io:: Repeat § impl Send for Sink § impl Send for Stderr § impl Send for Stdin § impl Send for Stdout § impl Send for WriterPanicked § impl Send for Assume § impl Send for AddrParseError § impl Send for IntoIncoming § impl Send for Ipv4Addr § impl Send for Ipv6Addr § impl Send for SocketAddrV4 § impl Send for SocketAddrV6 § impl Send for TcpListener § impl Send for TcpStream § impl Send for UdpSocket § impl Send for ParseFloatError § impl Send for ParseIntError § impl Send for TryFromIntError § impl Send for RangeFull § impl Send for OwnedFd § impl Send for PidFd § impl Send for stat § impl Send for std::os::unix::net:: SocketAddr § impl Send for SocketCred § impl Send for UCred § impl Send for UnixDatagram § impl Send for UnixListener § impl Send for UnixStream § impl Send for InvalidHandleError § impl Send for NullHandleError § impl Send for OwnedSocket § impl Send for NormalizeError § impl Send for Path § impl Send for PathBuf § impl Send for StripPrefixError § impl Send for Child § impl Send for ChildStderr § impl Send for ChildStdin § impl Send for ChildStdout § impl Send for Command § impl Send for ExitCode § impl Send for ExitStatus § impl Send for ExitStatusError § impl Send for Output § impl Send for Stdio § impl Send for std::ptr:: Alignment § impl Send for DefaultRandomSource § impl Send for ParseBoolError § impl Send for Utf8Error § impl Send for FromUtf8Error § impl Send for FromUtf16Error § impl Send for IntoChars § impl Send for String § impl Send for AtomicBool § impl Send for AtomicI8 § impl Send for AtomicI16 § impl Send for AtomicI32 § impl Send for AtomicI64 § impl Send for AtomicIsize § impl Send for AtomicU8 § impl Send for AtomicU16 § impl Send for AtomicU32 § impl Send for AtomicU64 § impl Send for AtomicUsize § impl Send for RecvError § impl Send for std::sync::nonpoison:: Condvar § impl Send for WouldBlock § impl Send for Barrier § impl Send for BarrierWaitResult § impl Send for std::sync:: Condvar § impl Send for std::sync:: Once § impl Send for OnceState § impl Send for WaitTimeoutResult § impl Send for RawWakerVTable § impl Send for AccessError § impl Send for Builder § impl Send for Thread § impl Send for ThreadId § impl Send for Duration § impl Send for Instant § impl Send for SystemTime § impl Send for SystemTimeError § impl Send for TryFromFloatSecsError § impl Send for PhantomPinned § impl<'a> ! Send for Request <'a> § impl<'a> ! Send for Formatter <'a> § impl<'a> ! Send for StderrLock <'a> § impl<'a> ! Send for StdinLock <'a> § impl<'a> ! Send for StdoutLock <'a> § impl<'a> ! Send for ProcThreadAttributeListBuilder <'a> § impl<'a> ! Send for PanicHookInfo <'a> § impl<'a> ! Send for CommandArgs <'a> § impl<'a> ! Send for Context <'a> § impl<'a> ! Send for ContextBuilder <'a> § impl<'a> Send for AncillaryData <'a> § impl<'a> Send for Component <'a> § impl<'a> Send for Prefix <'a> § impl<'a> Send for Utf8Pattern <'a> § impl<'a> Send for SplitPaths <'a> § impl<'a> Send for std::ffi::os_str:: Display <'a> § impl<'a> Send for BorrowedCursor <'a> § impl<'a> Send for std::net:: Incoming <'a> § impl<'a> Send for std::os::unix::net:: Incoming <'a> § impl<'a> Send for Messages <'a> § impl<'a> Send for ScmCredentials <'a> § impl<'a> Send for ScmRights <'a> § impl<'a> Send for SocketAncillary <'a> § impl<'a> Send for EncodeWide <'a> § impl<'a> Send for ProcThreadAttributeList <'a> § impl<'a> Send for Ancestors <'a> § impl<'a> Send for Components <'a> § impl<'a> Send for std::path:: Display <'a> § impl<'a> Send for std::path:: Iter <'a> § impl<'a> Send for PrefixComponent <'a> § impl<'a> Send for CommandEnvs <'a> § impl<'a> Send for EscapeAscii <'a> § impl<'a> Send for CharSearcher <'a> § impl<'a> Send for std::str:: Bytes <'a> § impl<'a> Send for CharIndices <'a> § impl<'a> Send for Chars <'a> § impl<'a> Send for EncodeUtf16 <'a> § impl<'a> Send for std::str:: EscapeDebug <'a> § impl<'a> Send for std::str:: EscapeDefault <'a> § impl<'a> Send for std::str:: EscapeUnicode <'a> § impl<'a> Send for std::str:: Lines <'a> § impl<'a> Send for LinesAny <'a> § impl<'a> Send for SplitAsciiWhitespace <'a> § impl<'a> Send for SplitWhitespace <'a> § impl<'a> Send for Utf8Chunk <'a> § impl<'a> Send for Utf8Chunks <'a> § impl<'a> Send for PhantomContravariantLifetime <'a> § impl<'a> Send for PhantomCovariantLifetime <'a> § impl<'a> Send for PhantomInvariantLifetime <'a> § impl<'a, 'b> ! Send for DebugList <'a, 'b> § impl<'a, 'b> ! Send for DebugMap <'a, 'b> § impl<'a, 'b> ! Send for DebugSet <'a, 'b> § impl<'a, 'b> ! Send for DebugStruct <'a, 'b> § impl<'a, 'b> ! Send for DebugTuple <'a, 'b> § impl<'a, 'b> Send for CharSliceSearcher <'a, 'b> § impl<'a, 'b> Send for StrSearcher <'a, 'b> § impl<'a, 'b, const N: usize > Send for CharArrayRefSearcher <'a, 'b, N> § impl<'a, 'f> ! Send for VaList <'a, 'f> § impl<'a, A> Send for std::option:: Iter <'a, A> where A: Sync , § impl<'a, A> Send for std::option:: IterMut <'a, A> where A: Send , § impl<'a, B> Send for Cow <'a, B> where <B as ToOwned >:: Owned : Send , B: Sync + ? Sized , § impl<'a, F> Send for CharPredicateSearcher <'a, F> where F: Send , § impl<'a, I> Send for ByRefSized <'a, I> where I: Send , § impl<'a, I, A> Send for Splice <'a, I, A> where I: Send , <I as Iterator >:: Item : Send , A: Send , § impl<'a, K> Send for std::collections::btree_set:: Cursor <'a, K> where K: Sync , § impl<'a, K> Send for std::collections::hash_set:: Drain <'a, K> where K: Send , § impl<'a, K> Send for std::collections::hash_set:: Iter <'a, K> where K: Sync , § impl<'a, K, A> Send for std::collections::btree_set:: CursorMut <'a, K, A> where A: Send , K: Send , § impl<'a, K, A> Send for std::collections::btree_set:: CursorMutKey <'a, K, A> where A: Send , K: Send , § impl<'a, K, F> Send for std::collections::hash_set:: ExtractIf <'a, K, F> where F: Send , K: Send , § impl<'a, K, V> Send for std::collections::hash_map:: Entry <'a, K, V> where K: Send , V: Send , § impl<'a, K, V> Send for std::collections::btree_map:: Cursor <'a, K, V> where K: Sync , V: Sync , § impl<'a, K, V> Send for std::collections::btree_map:: Iter <'a, K, V> where K: Sync , V: Sync , § impl<'a, K, V> Send for std::collections::btree_map:: IterMut <'a, K, V> where K: Send , V: Send , § impl<'a, K, V> Send for std::collections::btree_map:: Keys <'a, K, V> where K: Sync , V: Sync , § impl<'a, K, V> Send for std::collections::btree_map:: Range <'a, K, V> where K: Sync , V: Sync , § impl<'a, K, V> Send for RangeMut <'a, K, V> where K: Send , V: Send , § impl<'a, K, V> Send for std::collections::btree_map:: Values <'a, K, V> where K: Sync , V: Sync , § impl<'a, K, V> Send for std::collections::btree_map:: ValuesMut <'a, K, V> where K: Send , V: Send , § impl<'a, K, V> Send for std::collections::hash_map:: Drain <'a, K, V> where K: Send , V: Send , § impl<'a, K, V> Send for std::collections::hash_map:: Iter <'a, K, V> where K: Sync , V: Sync , § impl<'a, K, V> Send for std::collections::hash_map:: IterMut <'a, K, V> where K: Send , V: Send , § impl<'a, K, V> Send for std::collections::hash_map:: Keys <'a, K, V> where K: Sync , V: Sync , § impl<'a, K, V> Send for std::collections::hash_map:: OccupiedEntry <'a, K, V> where K: Send , V: Send , § impl<'a, K, V> Send for std::collections::hash_map:: OccupiedError <'a, K, V> where V: Send , K: Send , § impl<'a, K, V> Send for std::collections::hash_map:: VacantEntry <'a, K, V> where K: Send , V: Send , § impl<'a, K, V> Send for std::collections::hash_map:: Values <'a, K, V> where K: Sync , V: Sync , § impl<'a, K, V> Send for std::collections::hash_map:: ValuesMut <'a, K, V> where K: Send , V: Send , § impl<'a, K, V, A> Send for std::collections::btree_map:: Entry <'a, K, V, A> where K: Send , A: Send , V: Send , § impl<'a, K, V, A> Send for std::collections::btree_map:: CursorMut <'a, K, V, A> where A: Send , K: Send , V: Send , § impl<'a, K, V, A> Send for std::collections::btree_map:: CursorMutKey <'a, K, V, A> where A: Send , K: Send , V: Send , § impl<'a, K, V, A> Send for std::collections::btree_map:: OccupiedEntry <'a, K, V, A> where A: Send , K: Send , V: Send , § impl<'a, K, V, A> Send for std::collections::btree_map:: OccupiedError <'a, K, V, A> where V: Send , A: Send , K: Send , § impl<'a, K, V, A> Send for std::collections::btree_map:: VacantEntry <'a, K, V, A> where K: Send , A: Send , V: Send , § impl<'a, K, V, F> Send for std::collections::hash_map:: ExtractIf <'a, K, V, F> where F: Send , K: Send , V: Send , § impl<'a, K, V, R, F, A> Send for std::collections::btree_map:: ExtractIf <'a, K, V, R, F, A> where F: Send , A: Send , R: Send , K: Send , V: Send , § impl<'a, P> Send for MatchIndices <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, P> Send for Matches <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, P> Send for RMatchIndices <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, P> Send for RMatches <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, P> Send for std::str:: RSplit <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, P> Send for std::str:: RSplitN <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, P> Send for RSplitTerminator <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, P> Send for std::str:: Split <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, P> Send for std::str:: SplitInclusive <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, P> Send for std::str:: SplitN <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, P> Send for SplitTerminator <'a, P> where <P as Pattern >:: Searcher <'a>: Send , § impl<'a, T> ! Send for std::sync::mpsc:: Iter <'a, T> § impl<'a, T> ! Send for std::sync::mpsc:: TryIter <'a, T> § impl<'a, T> Send for std::collections::binary_heap:: Iter <'a, T> where T: Sync , § impl<'a, T> Send for std::collections::btree_set:: Iter <'a, T> where T: Sync , § impl<'a, T> Send for std::collections::btree_set:: Range <'a, T> where T: Sync , § impl<'a, T> Send for std::collections::btree_set:: SymmetricDifference <'a, T> where T: Sync , § impl<'a, T> Send for std::collections::btree_set:: Union <'a, T> where T: Sync , § impl<'a, T> Send for std::collections::vec_deque:: Iter <'a, T> where T: Sync , § impl<'a, T> Send for std::collections::vec_deque:: IterMut <'a, T> where T: Send , § impl<'a, T> Send for std::result:: Iter <'a, T> where T: Sync , § impl<'a, T> Send for std::result:: IterMut <'a, T> where T: Send , § impl<'a, T> Send for Chunks <'a, T> where T: Sync , § impl<'a, T> Send for ChunksExact <'a, T> where T: Sync , § impl<'a, T> Send for RChunks <'a, T> where T: Sync , § impl<'a, T> Send for RChunksExact <'a, T> where T: Sync , § impl<'a, T> Send for Windows <'a, T> where T: Sync , § impl<'a, T> Send for std::sync::mpmc:: Iter <'a, T> where T: Send , § impl<'a, T> Send for std::sync::mpmc:: TryIter <'a, T> where T: Send , § impl<'a, T, A> Send for std::collections::btree_set:: Entry <'a, T, A> where A: Send , T: Send , § impl<'a, T, A> Send for std::collections::binary_heap:: Drain <'a, T, A> where T: Send , A: Send , § impl<'a, T, A> Send for DrainSorted <'a, T, A> where A: Send , T: Send , § impl<'a, T, A> Send for std::collections::binary_heap:: PeekMut <'a, T, A> where A: Send , T: Send , § impl<'a, T, A> Send for std::collections::btree_set:: Difference <'a, T, A> where T: Sync , A: Sync , § impl<'a, T, A> Send for std::collections::btree_set:: Intersection <'a, T, A> where T: Sync , A: Sync , § impl<'a, T, A> Send for std::collections::btree_set:: OccupiedEntry <'a, T, A> where A: Send , T: Send , § impl<'a, T, A> Send for std::collections::btree_set:: VacantEntry <'a, T, A> where T: Send , A: Send , § impl<'a, T, A> Send for std::vec:: PeekMut <'a, T, A> where A: Send , T: Send , § impl<'a, T, F, A = Global > ! Send for std::collections::linked_list:: ExtractIf <'a, T, F, A> § impl<'a, T, F, A> Send for std::vec:: ExtractIf <'a, T, F, A> where F: Send , A: Send , T: Send , § impl<'a, T, P> Send for ChunkBy <'a, T, P> where P: Send , T: Sync , § impl<'a, T, P> Send for ChunkByMut <'a, T, P> where P: Send , T: Send , § impl<'a, T, P> Send for std::slice:: RSplit <'a, T, P> where P: Send , T: Sync , § impl<'a, T, P> Send for RSplitMut <'a, T, P> where P: Send , T: Send , § impl<'a, T, P> Send for std::slice:: RSplitN <'a, T, P> where P: Send , T: Sync , § impl<'a, T, P> Send for RSplitNMut <'a, T, P> where P: Send , T: Send , § impl<'a, T, P> Send for std::slice:: Split <'a, T, P> where P: Send , T: Sync , § impl<'a, T, P> Send for std::slice:: SplitInclusive <'a, T, P> where P: Send , T: Sync , § impl<'a, T, P> Send for SplitInclusiveMut <'a, T, P> where P: Send , T: Send , § impl<'a, T, P> Send for SplitMut <'a, T, P> where P: Send , T: Send , § impl<'a, T, P> Send for std::slice:: SplitN <'a, T, P> where P: Send , T: Sync , § impl<'a, T, P> Send for SplitNMut <'a, T, P> where P: Send , T: Send , § impl<'a, T, R, F, A> Send for std::collections::btree_set:: ExtractIf <'a, T, R, F, A> where F: Send , A: Send , R: Send , T: Send , § impl<'a, T, S> Send for std::collections::hash_set:: Entry <'a, T, S> where T: Send , S: Send , § impl<'a, T, S> Send for std::collections::hash_set:: Difference <'a, T, S> where S: Sync , T: Sync , § impl<'a, T, S> Send for std::collections::hash_set:: Intersection <'a, T, S> where S: Sync , T: Sync , § impl<'a, T, S> Send for std::collections::hash_set:: OccupiedEntry <'a, T, S> where T: Send , S: Send , § impl<'a, T, S> Send for std::collections::hash_set:: SymmetricDifference <'a, T, S> where S: Sync , T: Sync , § impl<'a, T, S> Send for std::collections::hash_set:: Union <'a, T, S> where S: Sync , T: Sync , § impl<'a, T, S> Send for std::collections::hash_set:: VacantEntry <'a, T, S> where T: Send , S: Send , § impl<'a, T, const N: usize > Send for ArrayWindows <'a, T, N> where T: Sync , § impl<'a, const N: usize > Send for CharArraySearcher <'a, N> § impl<'b, T> ! Send for Ref <'b, T> § impl<'b, T> ! Send for RefMut <'b, T> § impl<'data> Send for BorrowedBuf <'data> § impl<'f> ! Send for VaListImpl <'f> § impl<'fd> Send for BorrowedFd <'fd> § impl<'scope, 'env> Send for Scope <'scope, 'env> § impl<'scope, T> Send for ScopedJoinHandle <'scope, T> where T: Send , § impl<'socket> Send for BorrowedSocket <'socket> § impl<A> Send for std::iter:: Repeat <A> where A: Send , § impl<A> Send for RepeatN <A> where A: Send , § impl<A> Send for std::option:: IntoIter <A> where A: Send , § impl<A> Send for IterRange <A> where A: Send , § impl<A> Send for IterRangeFrom <A> where A: Send , § impl<A> Send for IterRangeInclusive <A> where A: Send , § impl<A, B> Send for std::iter:: Chain <A, B> where A: Send , B: Send , § impl<A, B> Send for Zip <A, B> where A: Send , B: Send , § impl<B> Send for std::io:: Lines <B> where B: Send , § impl<B> Send for std::io:: Split <B> where B: Send , § impl<B, C> Send for ControlFlow <B, C> where C: Send , B: Send , § impl<E> Send for Report <E> where E: Send , § impl<F> Send for std::fmt:: FromFn <F> where F: Send , § impl<F> Send for PollFn <F> where F: Send , § impl<F> Send for std::iter:: FromFn <F> where F: Send , § impl<F> Send for OnceWith <F> where F: Send , § impl<F> Send for RepeatWith <F> where F: Send , § impl<G> Send for FromCoroutine <G> where G: Send , § impl<H> Send for BuildHasherDefault <H> § impl<I> Send for FromIter <I> where I: Send , § impl<I> Send for DecodeUtf16 <I> where I: Send , § impl<I> Send for Cloned <I> where I: Send , § impl<I> Send for Copied <I> where I: Send , § impl<I> Send for Cycle <I> where I: Send , § impl<I> Send for Enumerate <I> where I: Send , § impl<I> Send for Flatten <I> where <<I as Iterator >:: Item as IntoIterator >:: IntoIter : Send , I: Send , § impl<I> Send for Fuse <I> where I: Send , § impl<I> Send for Intersperse <I> where <I as Iterator >:: Item : Sized + Send , I: Send , § impl<I> Send for Peekable <I> where I: Send , <I as Iterator >:: Item : Send , § impl<I> Send for Skip <I> where I: Send , § impl<I> Send for StepBy <I> where I: Send , § impl<I> Send for std::iter:: Take <I> where I: Send , § impl<I, F> Send for FilterMap <I, F> where I: Send , F: Send , § impl<I, F> Send for Inspect <I, F> where I: Send , F: Send , § impl<I, F> Send for Map <I, F> where I: Send , F: Send , § impl<I, F, const N: usize > Send for MapWindows <I, F, N> where F: Send , I: Send , <I as Iterator >:: Item : Send , § impl<I, G> Send for IntersperseWith <I, G> where G: Send , <I as Iterator >:: Item : Send , I: Send , § impl<I, P> Send for Filter <I, P> where I: Send , P: Send , § impl<I, P> Send for MapWhile <I, P> where I: Send , P: Send , § impl<I, P> Send for SkipWhile <I, P> where I: Send , P: Send , § impl<I, P> Send for TakeWhile <I, P> where I: Send , P: Send , § impl<I, St, F> Send for Scan <I, St, F> where I: Send , F: Send , St: Send , § impl<I, U, F> Send for FlatMap <I, U, F> where <U as IntoIterator >:: IntoIter : Send , I: Send , F: Send , § impl<I, const N: usize > Send for ArrayChunks <I, N> where I: Send , <I as Iterator >:: Item : Send , § impl<Idx> Send for std::ops:: Range <Idx> where Idx: Send , § impl<Idx> Send for std::ops:: RangeFrom <Idx> where Idx: Send , § impl<Idx> Send for std::ops:: RangeInclusive <Idx> where Idx: Send , § impl<Idx> Send for RangeTo <Idx> where Idx: Send , § impl<Idx> Send for std::ops:: RangeToInclusive <Idx> where Idx: Send , § impl<Idx> Send for std::range:: Range <Idx> where Idx: Send , § impl<Idx> Send for std::range:: RangeFrom <Idx> where Idx: Send , § impl<Idx> Send for std::range:: RangeInclusive <Idx> where Idx: Send , § impl<Idx> Send for std::range:: RangeToInclusive <Idx> where Idx: Send , § impl<K> Send for std::collections::hash_set:: IntoIter <K> where K: Send , § impl<K, V> Send for std::collections::hash_map:: IntoIter <K, V> where K: Send , V: Send , § impl<K, V> Send for std::collections::hash_map:: IntoKeys <K, V> where K: Send , V: Send , § impl<K, V> Send for std::collections::hash_map:: IntoValues <K, V> where K: Send , V: Send , § impl<K, V, A> Send for std::collections::btree_map:: IntoIter <K, V, A> where A: Send , K: Send , V: Send , § impl<K, V, A> Send for std::collections::btree_map:: IntoKeys <K, V, A> where A: Send , K: Send , V: Send , § impl<K, V, A> Send for std::collections::btree_map:: IntoValues <K, V, A> where A: Send , K: Send , V: Send , § impl<K, V, A> Send for BTreeMap <K, V, A> where A: Send , K: Send , V: Send , § impl<K, V, S> Send for HashMap <K, V, S> where S: Send , K: Send , V: Send , § impl<Ptr> Send for Pin <Ptr> where Ptr: Send , § impl<R> Send for BufReader <R> where R: Send + ? Sized , § impl<R> Send for std::io:: Bytes <R> where R: Send , § impl<Ret, T> Send for fn(T₁, T₂, …, Tₙ) -> Ret § impl<T> Send for Bound <T> where T: Send , § impl<T> Send for Option <T> where T: Send , § impl<T> Send for std::sync:: TryLockError <T> where T: Send , § impl<T> Send for SendTimeoutError <T> where T: Send , § impl<T> Send for TrySendError <T> where T: Send , § impl<T> Send for Poll <T> where T: Send , § impl<T> Send for [T] where T: Send , § impl<T> Send for (T₁, T₂, …, Tₙ) where T: Send , § impl<T> Send for OnceCell <T> where T: Send , § impl<T> Send for SyncUnsafeCell <T> where T: Send + ? Sized , § impl<T> Send for UnsafeCell <T> where T: Send + ? Sized , § impl<T> Send for Reverse <T> where T: Send , § impl<T> Send for Pending <T> § impl<T> Send for Ready <T> where T: Send , § impl<T> Send for std::io:: Cursor <T> where T: Send , § impl<T> Send for std::io:: Take <T> where T: Send , § impl<T> Send for std::iter:: Empty <T> § impl<T> Send for std::iter:: Once <T> where T: Send , § impl<T> Send for Rev <T> where T: Send , § impl<T> Send for Discriminant <T> § impl<T> Send for ManuallyDrop <T> where T: Send + ? Sized , § impl<T> Send for Saturating <T> where T: Send , § impl<T> Send for Wrapping <T> where T: Send , § impl<T> Send for Yeet <T> where T: Send , § impl<T> Send for AssertUnwindSafe <T> where T: Send , § impl<T> Send for UnsafePinned <T> where T: Send + ? Sized , § impl<T> Send for std::result:: IntoIter <T> where T: Send , § impl<T> Send for std::sync::mpmc:: IntoIter <T> where T: Send , § impl<T> Send for std::sync::mpsc:: IntoIter <T> where T: Send , § impl<T> Send for SendError <T> where T: Send , § impl<T> Send for Exclusive <T> where T: Send + ? Sized , § impl<T> Send for PoisonError <T> where T: Send , § impl<T> Send for LocalKey <T> § impl<T> Send for PhantomContravariant <T> where T: ? Sized , § impl<T> Send for PhantomCovariant <T> where T: ? Sized , § impl<T> Send for PhantomData <T> where T: Send + ? Sized , § impl<T> Send for PhantomInvariant <T> where T: ? Sized , § impl<T> Send for MaybeUninit <T> where T: Send , § impl<T, A> Send for Box <T, A> where A: Send , T: Send + ? Sized , § impl<T, A> Send for std::collections::binary_heap:: IntoIter <T, A> where T: Send , A: Send , § impl<T, A> Send for IntoIterSorted <T, A> where A: Send , T: Send , § impl<T, A> Send for std::collections::btree_set:: IntoIter <T, A> where A: Send , T: Send , § impl<T, A> Send for std::collections::linked_list:: IntoIter <T, A> where T: Send , A: Send , § impl<T, A> Send for BTreeSet <T, A> where A: Send , T: Send , § impl<T, A> Send for BinaryHeap <T, A> where A: Send , T: Send , § impl<T, A> Send for VecDeque <T, A> where A: Send , T: Send , § impl<T, A> Send for std::collections::vec_deque:: IntoIter <T, A> where A: Send , T: Send , § impl<T, A> Send for Vec <T, A> where A: Send , T: Send , § impl<T, E> Send for Result <T, E> where T: Send , E: Send , § impl<T, F> Send for LazyCell <T, F> where F: Send , T: Send , § impl<T, F> Send for Successors <T, F> where F: Send , T: Send , § impl<T, F> Send for DropGuard <T, F> where T: Send , F: Send , § impl<T, F> Send for LazyLock <T, F> where T: Send , F: Send , § impl<T, S> Send for HashSet <T, S> where S: Send , T: Send , § impl<T, U> Send for std::io:: Chain <T, U> where T: Send , U: Send , § impl<T, const N: usize > Send for [T; N] where T: Send , § impl<T, const N: usize > Send for std::array:: IntoIter <T, N> where T: Send , § impl<T, const N: usize > Send for Mask <T, N> where T: Send , § impl<T, const N: usize > Send for Simd <T, N> where T: Send , § impl<T, const N: usize > Send for [ Option <T>; N ] where T: Send , § impl<T, const N: usize > Send for [ MaybeUninit <T>; N ] where T: Send , § impl<W> Send for BufWriter <W> where W: Send + ? Sized , § impl<W> Send for IntoInnerError <W> where W: Send , § impl<W> Send for LineWriter <W> where W: Send + ? Sized , § impl<Y, R> Send for CoroutineState <Y, R> where Y: Send , R: Send , § impl<const N: usize > Send for LaneCount <N> § impl<const N: usize > Send for [ u8 ; N ] | 2026-01-13T09:29:13 |
https://fr-fr.facebook.com/reg/?entry_point=login&amp%3Bnext=https%3A%2F%2Fwww.facebook.com%2Fshare_channel%2F%3Ftype%3Dreshare%26link%3Dhttps%253A%252F%252Fdev.to%252Ftauri%252Ftauri-10-release-candidate-53jk%26app_id%3D966242223397117%26source_surface%3Dexternal_reshare%26display%26hashtag | 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://bsky.app/profile/ben.balter.com | @ben.balter.com on Bluesky JavaScript Required This is a heavily interactive web application, and JavaScript is required. Simple HTML interfaces are possible, but that is not what this is. Learn more about Bluesky at bsky.social and atproto.com . Profile Ben Balter ben.balter.com did:plc:dw6j5wx7vyzjxxoauzdbim6w Director of Hubber Enablement at @GitHub. Previously @GitHub Engineering, Security, Trust & Safety leader, and before that @PIFgov. Legacy blue check in Washington, D.C. | 2026-01-13T09:29:13 |
https://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b1-spdx-license-list-matching-guidelines | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 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%3DAT3JYaROIHDRnGnvxRuIozFF_BGGvvoNi8kVPWnSK0yCW2_Va2rKJWNXZ3PUqk5CKpNtOfbF-WNUpIWc7WVvePlsk9n9z3ptr24Okxk2028tZW0HuZ3QVvGoPKfc7Ts55I89ELD7U7OWf7bu | 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://pt-br.facebook.com/reg/?entry_point=login&amp%3Bnext=https%3A%2F%2Fwww.facebook.com%2Fshare_channel%2F%3Ftype%3Dreshare%26link%3Dhttps%253A%252F%252Fdev.to%252Ftauri%252Ftauri-10-release-candidate-53jk%26app_id%3D966242223397117%26source_surface%3Dexternal_reshare%26display%26hashtag | 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://ja-jp.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT3JYaROIHDRnGnvxRuIozFF_BGGvvoNi8kVPWnSK0yCW2_Va2rKJWNXZ3PUqk5CKpNtOfbF-WNUpIWc7WVvePlsk9n9z3ptr24Okxk2028tZW0HuZ3QVvGoPKfc7Ts55I89ELD7U7OWf7bu | 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/ptr/fn.read.html | read in std::ptr - Rust This old browser is unsupported and will most likely display funky things. read std 1.92.0 (ded5c06cf 2025-12-08) read Sections Safety Examples Ownership of the Returned Value In std:: ptr std :: ptr Function read Copy item path 1.0.0 (const: 1.71.0) · Source pub const unsafe fn read<T>(src: *const T ) -> T Expand description Reads the value from src without moving it. This leaves the memory in src unchanged. § Safety Behavior is undefined if any of the following conditions are violated: src must be valid for reads. src must be properly aligned. Use read_unaligned if this is not the case. src must point to a properly initialized value of type T . Note that even if T has size 0 , the pointer must be properly aligned. § Examples Basic usage: let x = 12 ; let y = & x as *const i32; unsafe { assert_eq! (std::ptr::read(y), 12 ); } Manually implement mem::swap : use std::ptr; fn swap<T>(a: &mut T, b: &mut T) { unsafe { // Create a bitwise copy of the value at `a` in `tmp`. let tmp = ptr::read(a); // Exiting at this point (either by explicitly returning or by // calling a function which panics) would cause the value in `tmp` to // be dropped while the same value is still referenced by `a`. This // could trigger undefined behavior if `T` is not `Copy`. // Create a bitwise copy of the value at `b` in `a`. // This is safe because mutable references cannot alias. ptr::copy_nonoverlapping(b, a, 1 ); // As above, exiting here could trigger undefined behavior because // the same value is referenced by `a` and `b`. // Move `tmp` into `b`. ptr::write(b, tmp); // `tmp` has been moved (`write` takes ownership of its second argument), // so nothing is dropped implicitly here. } } let mut foo = "foo" .to_owned(); let mut bar = "bar" .to_owned(); swap( &mut foo, &mut bar); assert_eq! (foo, "bar" ); assert_eq! (bar, "foo" ); § Ownership of the Returned Value read creates a bitwise copy of T , regardless of whether T is Copy . If T is not Copy , using both the returned value and the value at *src can violate memory safety. Note that assigning to *src counts as a use because it will attempt to drop the value at *src . write() can be used to overwrite data without causing it to be dropped. use std::ptr; let mut s = String::from( "foo" ); unsafe { // `s2` now points to the same underlying memory as `s`. let mut s2: String = ptr::read( & s); assert_eq! (s2, "foo" ); // Assigning to `s2` causes its original value to be dropped. Beyond // this point, `s` must no longer be used, as the underlying memory has // been freed. s2 = String::default(); assert_eq! (s2, "" ); // Assigning to `s` would cause the old value to be dropped again, // resulting in undefined behavior. // s = String::from("bar"); // ERROR // `ptr::write` can be used to overwrite a value without dropping it. ptr::write( &mut s, String::from( "bar" )); } assert_eq! (s, "bar" ); | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/std/convert/trait.TryFrom.html | TryFrom in std::convert - Rust This old browser is unsupported and will most likely display funky things. TryFrom std 1.92.0 (ded5c06cf 2025-12-08) TryFrom Sections Generic Implementations Examples Required Associated Types Error Required Methods try_from Dyn Compatibility Implementors In std:: convert std :: convert Trait TryFrom Copy item path 1.34.0 (const: unstable ) · Source pub trait TryFrom<T>: Sized { type Error ; // Required method fn try_from (value: T) -> Result <Self, Self:: Error >; } Expand description Simple and safe type conversions that may fail in a controlled way under some circumstances. It is the reciprocal of TryInto . This is useful when you are doing a type conversion that may trivially succeed but may also need special handling. For example, there is no way to convert an i64 into an i32 using the From trait, because an i64 may contain a value that an i32 cannot represent and so the conversion would lose data. This might be handled by truncating the i64 to an i32 or by simply returning i32::MAX , or by some other method. The From trait is intended for perfect conversions, so the TryFrom trait informs the programmer when a type conversion could go bad and lets them decide how to handle it. § Generic Implementations TryFrom<T> for U implies TryInto <U> for T try_from is reflexive, which means that TryFrom<T> for T is implemented and cannot fail – the associated Error type for calling T::try_from() on a value of type T is Infallible . When the ! type is stabilized Infallible and ! will be equivalent. Prefer using TryInto over TryFrom when specifying trait bounds on a generic function to ensure that types that only implement TryInto can be used as well. TryFrom<T> can be implemented as follows: struct GreaterThanZero(i32); impl TryFrom<i32> for GreaterThanZero { type Error = & 'static str; fn try_from(value: i32) -> Result < Self , Self ::Error> { if value <= 0 { Err ( "GreaterThanZero only accepts values greater than zero!" ) } else { Ok (GreaterThanZero(value)) } } } § Examples As described, i32 implements TryFrom< i64 > : let big_number = 1_000_000_000_000i64 ; // Silently truncates `big_number`, requires detecting // and handling the truncation after the fact. let smaller_number = big_number as i32; assert_eq! (smaller_number, - 727379968 ); // Returns an error because `big_number` is too big to // fit in an `i32`. let try_smaller_number = i32::try_from(big_number); assert! (try_smaller_number.is_err()); // Returns `Ok(3)`. let try_successful_smaller_number = i32::try_from( 3 ); assert! (try_successful_smaller_number.is_ok()); Required Associated Types § 1.34.0 · Source type Error The type returned in the event of a conversion error. Required Methods § 1.34.0 · Source fn try_from (value: T) -> Result <Self, Self:: Error > Performs the conversion. Dyn Compatibility § This trait is not dyn compatible . In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe. Implementors § 1.59.0 (const: unstable ) · Source § impl TryFrom < char > for u8 Maps a char with code point in U+0000..=U+00FF to a byte in 0x00..=0xFF with same value, failing if the code point is greater than U+00FF. See impl From<u8> for char for details on the encoding. Source § type Error = TryFromCharError 1.74.0 (const: unstable ) · Source § impl TryFrom < char > for u16 Maps a char with code point in U+0000..=U+FFFF to a u16 in 0x0000..=0xFFFF with same value, failing if the code point is greater than U+FFFF. This corresponds to the UCS-2 encoding, as specified in ISO/IEC 10646:2003. Source § type Error = TryFromCharError 1.34.0 (const: unstable ) · Source § impl TryFrom < i8 > for u8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i8 > for u16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i8 > for u32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i8 > for u64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i8 > for u128 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i8 > for usize Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < i8 > for NonZero < i8 > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i16 > for i8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i16 > for u8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i16 > for u16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i16 > for u32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i16 > for u64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i16 > for u128 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i16 > for usize Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < i16 > for NonZero < i16 > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i32 > for i8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i32 > for i16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i32 > for isize Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i32 > for u8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i32 > for u16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i32 > for u32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i32 > for u64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i32 > for u128 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i32 > for usize Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < i32 > for NonZero < i32 > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i64 > for i8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i64 > for i16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i64 > for i32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i64 > for isize Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i64 > for u8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i64 > for u16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i64 > for u32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i64 > for u64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i64 > for u128 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i64 > for usize Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < i64 > for NonZero < i64 > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for i8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for i16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for i32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for i64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for isize Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for u8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for u16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for u32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for u64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for u128 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < i128 > for usize Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < i128 > for NonZero < i128 > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for i8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for i16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for i32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for i64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for i128 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for u8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for u16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for u32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for u64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for u128 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < isize > for usize Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < isize > for NonZero < isize > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u8 > for i8 Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < u8 > for NonZero < u8 > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u16 > for i8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u16 > for i16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u16 > for isize Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u16 > for u8 Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < u16 > for NonZero < u16 > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u32 > for char Source § type Error = CharTryFromError 1.34.0 (const: unstable ) · Source § impl TryFrom < u32 > for i8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u32 > for i16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u32 > for i32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u32 > for isize Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u32 > for u8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u32 > for u16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u32 > for usize Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < u32 > for NonZero < u32 > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u64 > for i8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u64 > for i16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u64 > for i32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u64 > for i64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u64 > for isize Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u64 > for u8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u64 > for u16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u64 > for u32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u64 > for usize Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < u64 > for NonZero < u64 > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for i8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for i16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for i32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for i64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for i128 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for isize Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for u8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for u16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for u32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for u64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < u128 > for usize Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < u128 > for NonZero < u128 > Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for i8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for i16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for i32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for i64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for i128 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for isize Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for u8 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for u16 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for u32 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for u64 Source § type Error = TryFromIntError 1.34.0 (const: unstable ) · Source § impl TryFrom < usize > for u128 Source § type Error = TryFromIntError 1.46.0 (const: unstable ) · Source § impl TryFrom < usize > for NonZero < usize > Source § type Error = TryFromIntError Source § impl TryFrom < usize > for Alignment Source § type Error = TryFromIntError Source § impl TryFrom < ByteString > for String Source § type Error = FromUtf8Error 1.85.0 · Source § impl TryFrom < CString > for String Source § type Error = IntoStringError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i8 >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i8 >> for NonZero < u16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i8 >> for NonZero < u32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i8 >> for NonZero < u64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i8 >> for NonZero < u128 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i8 >> for NonZero < usize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i16 >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i16 >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i16 >> for NonZero < u16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i16 >> for NonZero < u32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i16 >> for NonZero < u64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i16 >> for NonZero < u128 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i16 >> for NonZero < usize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i32 >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i32 >> for NonZero < i16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i32 >> for NonZero < isize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i32 >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i32 >> for NonZero < u16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i32 >> for NonZero < u32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i32 >> for NonZero < u64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i32 >> for NonZero < u128 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i32 >> for NonZero < usize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i64 >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i64 >> for NonZero < i16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i64 >> for NonZero < i32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i64 >> for NonZero < isize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i64 >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i64 >> for NonZero < u16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i64 >> for NonZero < u32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i64 >> for NonZero < u64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i64 >> for NonZero < u128 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i64 >> for NonZero < usize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < i16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < i32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < i64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < isize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < u16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < u32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < u64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < u128 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < i128 >> for NonZero < usize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < i16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < i32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < i64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < i128 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < u16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < u32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < u64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < u128 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < isize >> for NonZero < usize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u8 >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u16 >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u16 >> for NonZero < i16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u16 >> for NonZero < isize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u16 >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u32 >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u32 >> for NonZero < i16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u32 >> for NonZero < i32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u32 >> for NonZero < isize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u32 >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u32 >> for NonZero < u16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u32 >> for NonZero < usize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u64 >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u64 >> for NonZero < i16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u64 >> for NonZero < i32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u64 >> for NonZero < i64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u64 >> for NonZero < isize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u64 >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u64 >> for NonZero < u16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u64 >> for NonZero < u32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u64 >> for NonZero < usize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < i16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < i32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < i64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < i128 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < isize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < u16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < u32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < u64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < u128 >> for NonZero < usize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < i8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < i16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < i32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < i64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < i128 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < isize > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < u8 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < u16 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < u32 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < u64 > Source § type Error = TryFromIntError 1.49.0 (const: unstable ) · Source § impl TryFrom < NonZero < usize >> for NonZero < u128 > Source § type Error = TryFromIntError Source § impl TryFrom < NonZero < usize >> for Alignment Source § type Error = TryFromIntError 1.63.0 · Source § impl TryFrom < HandleOrInvalid > for OwnedHandle Available on Windows only. Source § type Error = InvalidHandleError 1.63.0 · Source § impl TryFrom < HandleOrNull > for OwnedHandle Available on Windows only. Source § type Error = NullHandleError 1.87.0 · Source § impl TryFrom < Vec < u8 >> for String Source § type Error = FromUtf8Error Source § impl<'a> TryFrom <&'a ByteStr > for &'a str Source § type Error = Utf8Error Source § impl<'a> TryFrom <&'a ByteStr > for String Source § type Error = Utf8Error Source § impl<'a> TryFrom <&'a ByteString > for &'a str Source § type Error = Utf8Error 1.72.0 · Source § impl<'a> TryFrom <&'a OsStr > for &'a str Source § type Error = Utf8Error Source § impl<'a> TryFrom <&'a mut ByteStr > for &'a mut str Source § type Error = Utf8Error 1.34.0 (const: unstable ) · Source § impl<'a, T, const N: usize > TryFrom <&'a [T] > for &'a [T; N] Tries to create an array ref &[T; N] from a slice ref &[T] . Succeeds if slice.len() == N . let bytes: [u8; 3 ] = [ 1 , 0 , 2 ]; let bytes_head: & [u8; 2 ] = < & [u8; 2 ]>::try_from( & bytes[ 0 .. 2 ]).unwrap(); assert_eq! ( 1 , u16::from_le_bytes( * bytes_head)); let bytes_tail: & [u8; 2 ] = bytes[ 1 .. 3 ].try_into().unwrap(); assert_eq! ( 512 , u16::from_le_bytes( * bytes_tail)); Source § type Error = TryFromSliceError 1.34.0 (const: unstable ) · Source § impl<'a, T, const N: usize > TryFrom <&'a mut [T] > for &'a mut [T; N] Tries to create a mutable array ref &mut [T; N] from a mutable slice ref &mut [T] . Succeeds if slice.len() == N . let mut bytes: [u8; 3 ] = [ 1 , 0 , 2 ]; let bytes_head: &mut [u8; 2 ] = < &mut [u8; 2 ]>::try_from( &mut bytes[ 0 .. 2 ]).unwrap(); assert_eq! ( 1 , u16::from_le_bytes( * bytes_head)); let bytes_tail: &mut [u8; 2 ] = ( &mut bytes[ 1 .. 3 ]).try_into().unwrap(); assert_eq! ( 512 , u16::from_le_bytes( * bytes_tail)); Source § type Error = TryFromSliceError 1.43.0 · Source § impl<T, A, const N: usize > TryFrom < Rc < [T] , A>> for Rc < [T; N] , A> where A: Allocator , Source § type Error = Rc < [T] , A> 1.43.0 · Source § impl<T, A, const N: usize > TryFrom < Arc < [T] , A>> for Arc < [T; N] , A> where A: Allocator , Source § type Error = Arc < [T] , A> 1.48.0 · Source § impl<T, A, const N: usize > TryFrom < Vec <T, A>> for [T; N] where A: Allocator , Source § type Error = Vec <T, A> 1.34.0 (const: unstable ) · Source § impl<T, U> TryFrom <U> for T where U: Into <T>, Source § type Error = Infallible 1.34.0 (const: unstable ) · Source § impl<T, const N: usize > TryFrom <& [T] > for [T; N] where T: Copy , Tries to create an array [T; N] by copying from a slice &[T] . Succeeds if slice.len() == N . let bytes: [u8; 3 ] = [ 1 , 0 , 2 ]; let bytes_head: [u8; 2 ] = <[u8; 2 ]>::try_from( & bytes[ 0 .. 2 ]).unwrap(); assert_eq! ( 1 , u16::from_le_bytes(bytes_head)); let bytes_tail: [u8; 2 ] = bytes[ 1 .. 3 ].try_into().unwrap(); assert_eq! ( 512 , u16::from_le_bytes(bytes_tail)); Source § type Error = TryFromSliceError Source § impl<T, const N: usize > TryFrom <& [T] > for Simd <T, N> where LaneCount <N>: SupportedLaneCount , T: SimdElement , Source § type Error = TryFromSliceError 1.59.0 (const: unstable ) · Source § impl<T, const N: usize > TryFrom <&mut [T] > for [T; N] where T: Copy , Tries to create an array [T; N] by copying from a mutable slice &mut [T] . Succeeds if slice.len() == N . let mut bytes: [u8; 3 ] = [ 1 , 0 , 2 ]; let bytes_head: [u8; 2 ] = <[u8; 2 ]>::try_from( &mut bytes[ 0 .. 2 ]).unwrap(); assert_eq! ( 1 , u16::from_le_bytes(bytes_head)); let bytes_tail: [u8; 2 ] = ( &mut bytes[ 1 .. 3 ]).try_into().unwrap(); assert_eq! ( 512 , u16::from_le_bytes(bytes_tail)); Source § type Error = TryFromSliceError Source § impl<T, const N: usize > TryFrom <&mut [T] > for Simd <T, N> where LaneCount <N>: SupportedLaneCount , T: SimdElement , Source § type Error = TryFromSliceError 1.43.0 · Source § impl<T, const N: usize > TryFrom < Box < [T] >> for Box < [T; N] > Source § type Error = Box < [T] > 1.66.0 · Source § impl<T, const N: usize > TryFrom < Vec <T>> for Box < [T; N] > Source § type Error = Vec <T> | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/std/thread/fn.spawn.html | spawn in std::thread - Rust This old browser is unsupported and will most likely display funky things. spawn std 1.92.0 (ded5c06cf 2025-12-08) spawn Sections Panics Examples Notes In std:: thread std :: thread Function spawn Copy item path 1.0.0 · Source pub fn spawn<F, T>(f: F) -> JoinHandle <T> where F: FnOnce () -> T + Send + 'static, T: Send + 'static, Expand description Spawns a new thread, returning a JoinHandle for it. The join handle provides a join method that can be used to join the spawned thread. If the spawned thread panics, join will return an Err containing the argument given to panic! . If the join handle is dropped, the spawned thread will implicitly be detached . In this case, the spawned thread may no longer be joined. (It is the responsibility of the program to either eventually join threads it creates or detach them; otherwise, a resource leak will result.) This function creates a thread with the default parameters of Builder . To specify the new thread’s stack size or the name, use Builder::spawn . As you can see in the signature of spawn there are two constraints on both the closure given to spawn and its return value, let’s explain them: The 'static constraint means that the closure and its return value must have a lifetime of the whole program execution. The reason for this is that threads can outlive the lifetime they have been created in. Indeed if the thread, and by extension its return value, can outlive their caller, we need to make sure that they will be valid afterwards, and since we can’t know when it will return we need to have them valid as long as possible, that is until the end of the program, hence the 'static lifetime. The Send constraint is because the closure will need to be passed by value from the thread where it is spawned to the new thread. Its return value will need to be passed from the new thread to the thread where it is join ed. As a reminder, the Send marker trait expresses that it is safe to be passed from thread to thread. Sync expresses that it is safe to have a reference be passed from thread to thread. § Panics Panics if the OS fails to create a thread; use Builder::spawn to recover from such errors. § Examples Creating a thread. use std::thread; let handler = thread::spawn(|| { // thread code }); handler.join().unwrap(); As mentioned in the module documentation, threads are usually made to communicate using channels , here is how it usually looks. This example also shows how to use move , in order to give ownership of values to a thread. use std::thread; use std::sync::mpsc::channel; let (tx, rx) = channel(); let sender = thread::spawn( move || { tx.send( "Hello, thread" .to_owned()) .expect( "Unable to send on channel" ); }); let receiver = thread::spawn( move || { let value = rx.recv().expect( "Unable to receive from channel" ); println! ( "{value}" ); }); sender.join().expect( "The sender thread has panicked" ); receiver.join().expect( "The receiver thread has panicked" ); A thread can also return a value through its JoinHandle , you can use this to make asynchronous computations (futures might be more appropriate though). use std::thread; let computation = thread::spawn(|| { // Some expensive computation. 42 }); let result = computation.join().unwrap(); println! ( "{result}" ); § Notes This function has the same minimal guarantee regarding “foreign” unwinding operations (e.g. an exception thrown from C++ code, or a panic! in Rust code compiled or linked with a different runtime) as catch_unwind ; namely, if the thread created with thread::spawn unwinds all the way to the root with such an exception, one of two behaviors are possible, and it is unspecified which will occur: The process aborts. The process does not abort, and join will return a Result::Err containing an opaque type. | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/macros.html#macros | Macros - 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 Macros Input syntax is evocative of the output (C-EVOCATIVE) Rust macros let you dream up practically whatever input syntax you want. Aim to keep input syntax familiar and cohesive with the rest of your users' code by mirroring existing Rust syntax where possible. Pay attention to the choice and placement of keywords and punctuation. A good guide is to use syntax, especially keywords and punctuation, that is similar to what will be produced in the output of the macro. For example if your macro declares a struct with a particular name given in the input, preface the name with the keyword struct to signal to readers that a struct is being declared with the given name. #![allow(unused)] fn main() { // Prefer this... bitflags! { struct S: u32 { /* ... */ } } // ...over no keyword... bitflags! { S: u32 { /* ... */ } } // ...or some ad-hoc word. bitflags! { flags S: u32 { /* ... */ } } } Another example is semicolons vs commas. Constants in Rust are followed by semicolons so if your macro declares a chain of constants, they should likely be followed by semicolons even if the syntax is otherwise slightly different from Rust's. #![allow(unused)] fn main() { // Ordinary constants use semicolons. const A: u32 = 0b000001; const B: u32 = 0b000010; // So prefer this... bitflags! { struct S: u32 { const C = 0b000100; const D = 0b001000; } } // ...over this. bitflags! { struct S: u32 { const E = 0b010000, const F = 0b100000, } } } Macros are so diverse that these specific examples won't be relevant, but think about how to apply the same principles to your situation. Item macros compose well with attributes (C-MACRO-ATTR) Macros that produce more than one output item should support adding attributes to any one of those items. One common use case would be putting individual items behind a cfg. #![allow(unused)] fn main() { bitflags! { struct Flags: u8 { #[cfg(windows)] const ControlCenter = 0b001; #[cfg(unix)] const Terminal = 0b010; } } } Macros that produce a struct or enum as output should support attributes so that the output can be used with derive. #![allow(unused)] fn main() { bitflags! { #[derive(Default, Serialize)] struct Flags: u8 { const ControlCenter = 0b001; const Terminal = 0b010; } } } Item macros work anywhere that items are allowed (C-ANYWHERE) Rust allows items to be placed at the module level or within a tighter scope like a function. Item macros should work equally well as ordinary items in all of these places. The test suite should include invocations of the macro in at least the module scope and function scope. #![allow(unused)] fn main() { #[cfg(test)] mod tests { test_your_macro_in_a!(module); #[test] fn anywhere() { test_your_macro_in_a!(function); } } } As a simple example of how things can go wrong, this macro works great in a module scope but fails in a function scope. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident :: $t:ident) => { pub struct $t; pub mod $m { pub use super::$t; } } } broken!(m::T); // okay, expands to T and m::T fn g() { broken!(m::U); // fails to compile, super::U refers to the containing module not g } } Item macros support visibility specifiers (C-MACRO-VIS) Follow Rust syntax for visibility of items produced by a macro. Private by default, public if pub is specified. #![allow(unused)] fn main() { bitflags! { struct PrivateFlags: u8 { const A = 0b0001; const B = 0b0010; } } bitflags! { pub struct PublicFlags: u8 { const C = 0b0100; const D = 0b1000; } } } Type fragments are flexible (C-MACRO-TY) If your macro accepts a type fragment like $t:ty in the input, it should be usable with all of the following: Primitives: u8 , &str Relative paths: m::Data Absolute paths: ::base::Data Upward relative paths: super::Data Generics: Vec<String> As a simple example of how things can go wrong, this macro works great with primitives and absolute paths but fails with relative paths. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident => $t:ty) => { pub mod $m { pub struct Wrapper($t); } } } broken!(a => u8); // okay broken!(b => ::std::marker::PhantomData<()>); // okay struct S; broken!(c => S); // fails to compile } | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/macros.html#input-syntax-is-evocative-of-the-output-c-evocative | Macros - 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 Macros Input syntax is evocative of the output (C-EVOCATIVE) Rust macros let you dream up practically whatever input syntax you want. Aim to keep input syntax familiar and cohesive with the rest of your users' code by mirroring existing Rust syntax where possible. Pay attention to the choice and placement of keywords and punctuation. A good guide is to use syntax, especially keywords and punctuation, that is similar to what will be produced in the output of the macro. For example if your macro declares a struct with a particular name given in the input, preface the name with the keyword struct to signal to readers that a struct is being declared with the given name. #![allow(unused)] fn main() { // Prefer this... bitflags! { struct S: u32 { /* ... */ } } // ...over no keyword... bitflags! { S: u32 { /* ... */ } } // ...or some ad-hoc word. bitflags! { flags S: u32 { /* ... */ } } } Another example is semicolons vs commas. Constants in Rust are followed by semicolons so if your macro declares a chain of constants, they should likely be followed by semicolons even if the syntax is otherwise slightly different from Rust's. #![allow(unused)] fn main() { // Ordinary constants use semicolons. const A: u32 = 0b000001; const B: u32 = 0b000010; // So prefer this... bitflags! { struct S: u32 { const C = 0b000100; const D = 0b001000; } } // ...over this. bitflags! { struct S: u32 { const E = 0b010000, const F = 0b100000, } } } Macros are so diverse that these specific examples won't be relevant, but think about how to apply the same principles to your situation. Item macros compose well with attributes (C-MACRO-ATTR) Macros that produce more than one output item should support adding attributes to any one of those items. One common use case would be putting individual items behind a cfg. #![allow(unused)] fn main() { bitflags! { struct Flags: u8 { #[cfg(windows)] const ControlCenter = 0b001; #[cfg(unix)] const Terminal = 0b010; } } } Macros that produce a struct or enum as output should support attributes so that the output can be used with derive. #![allow(unused)] fn main() { bitflags! { #[derive(Default, Serialize)] struct Flags: u8 { const ControlCenter = 0b001; const Terminal = 0b010; } } } Item macros work anywhere that items are allowed (C-ANYWHERE) Rust allows items to be placed at the module level or within a tighter scope like a function. Item macros should work equally well as ordinary items in all of these places. The test suite should include invocations of the macro in at least the module scope and function scope. #![allow(unused)] fn main() { #[cfg(test)] mod tests { test_your_macro_in_a!(module); #[test] fn anywhere() { test_your_macro_in_a!(function); } } } As a simple example of how things can go wrong, this macro works great in a module scope but fails in a function scope. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident :: $t:ident) => { pub struct $t; pub mod $m { pub use super::$t; } } } broken!(m::T); // okay, expands to T and m::T fn g() { broken!(m::U); // fails to compile, super::U refers to the containing module not g } } Item macros support visibility specifiers (C-MACRO-VIS) Follow Rust syntax for visibility of items produced by a macro. Private by default, public if pub is specified. #![allow(unused)] fn main() { bitflags! { struct PrivateFlags: u8 { const A = 0b0001; const B = 0b0010; } } bitflags! { pub struct PublicFlags: u8 { const C = 0b0100; const D = 0b1000; } } } Type fragments are flexible (C-MACRO-TY) If your macro accepts a type fragment like $t:ty in the input, it should be usable with all of the following: Primitives: u8 , &str Relative paths: m::Data Absolute paths: ::base::Data Upward relative paths: super::Data Generics: Vec<String> As a simple example of how things can go wrong, this macro works great with primitives and absolute paths but fails with relative paths. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident => $t:ty) => { pub mod $m { pub struct Wrapper($t); } } } broken!(a => u8); // okay broken!(b => ::std::marker::PhantomData<()>); // okay struct S; broken!(c => S); // fails to compile } | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/documentation.html#documentation | Documentation - 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 Documentation Crate level docs are thorough and include examples (C-CRATE-DOC) See RFC 1687 . All items have a rustdoc example (C-EXAMPLE) Every public module, trait, struct, enum, function, method, macro, and type definition should have an example that exercises the functionality. This guideline should be applied within reason. A link to an applicable example on another item may be sufficient. For example if exactly one function uses a particular type, it may be appropriate to write a single example on either the function or the type and link to it from the other. The purpose of an example is not always to show how to use the item. Readers can be expected to understand how to invoke functions, match on enums, and other fundamental tasks. Rather, an example is often intended to show why someone would want to use the item. // This would be a poor example of using clone(). It mechanically shows *how* to // call clone(), but does nothing to show *why* somebody would want this. fn main() { let hello = "hello"; hello.clone(); } Examples use ? , not try! , not unwrap (C-QUESTION-MARK) Like it or not, example code is often copied verbatim by users. Unwrapping an error should be a conscious decision that the user needs to make. A common way of structuring fallible example code is the following. The lines beginning with # are compiled by cargo test when building the example but will not appear in user-visible rustdoc. /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box<dyn Error>> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` Function docs include error, panic, and safety considerations (C-FAILURE) Error conditions should be documented in an "Errors" section. This applies to trait methods as well -- trait methods for which the implementation is allowed or expected to return an error should be documented with an "Errors" section. For example in the standard library, Some implementations of the std::io::Read::read trait method may return an error. /// Pull some bytes from this source into the specified buffer, returning /// how many bytes were read. /// /// ... lots more info ... /// /// # Errors /// /// If this function encounters any form of I/O or other error, an error /// variant will be returned. If an error is returned then it must be /// guaranteed that no bytes were read. Panic conditions should be documented in a "Panics" section. This applies to trait methods as well -- traits methods for which the implementation is allowed or expected to panic should be documented with a "Panics" section. In the standard library the Vec::insert method may panic. /// Inserts an element at position `index` within the vector, shifting all /// elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. It is not necessary to document all conceivable panic cases, especially if the panic occurs in logic provided by the caller. For example documenting the Display panic in the following code seems excessive. But when in doubt, err on the side of documenting more panic cases. #![allow(unused)] fn main() { /// # Panics /// /// This function panics if `T`'s implementation of `Display` panics. pub fn print<T: Display>(t: T) { println!("{}", t.to_string()); } } Unsafe functions should be documented with a "Safety" section that explains all invariants that the caller is responsible for upholding to use the function correctly. The unsafe std::ptr::read requires the following of the caller. /// Reads the value from `src` without moving it. This leaves the /// memory in `src` unchanged. /// /// # Safety /// /// Beyond accepting a raw pointer, this is unsafe because it semantically /// moves the value out of `src` without preventing further usage of `src`. /// If `T` is not `Copy`, then care must be taken to ensure that the value at /// `src` is not used before the data is overwritten again (e.g. with `write`, /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use /// because it will attempt to drop the value previously at `*src`. /// /// The pointer must be aligned; use `read_unaligned` if that is not the case. Prose contains hyperlinks to relevant things (C-LINK) Regular links can be added inline with the usual markdown syntax of [text](url) . Links to other types can be added by marking them with [`text`] , then adding the link target in a new line at the end of the docstring with [`text`]: <target> , where <target> is described below. Link targets to methods within the same type usually look like this: [`serialize_struct`]: #method.serialize_struct Link targets to other types usually look like this: [`Deserialize`]: trait.Deserialize.html Link targets may also point to a parent or child module: [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html This guideline is officially recommended by RFC 1574 under the heading "Link all the things" . Cargo.toml includes all common metadata (C-METADATA) The [package] section of Cargo.toml should include the following values: authors description license repository keywords categories In addition, there are two optional metadata fields: documentation homepage By default, crates.io links to documentation for the crate on docs.rs . The documentation metadata only needs to be set if the documentation is hosted somewhere other than docs.rs , for example because the crate links against a shared library that is not available in the build environment of docs.rs . The homepage metadata should only be set if there is a unique website for the crate other than the source repository or API documentation. Do not make homepage redundant with either the documentation or repository values. For example, serde sets homepage to https://serde.rs , a dedicated website. Release notes document all significant changes (C-RELNOTES) Users of the crate can read the release notes to find a summary of what changed in each published release of the crate. A link to the release notes, or the notes themselves, should be included in the crate-level documentation and/or the repository linked in Cargo.toml. Breaking changes (as defined in RFC 1105 ) should be clearly identified in the release notes. If using Git to track the source of a crate, every release published to crates.io should have a corresponding tag identifying the commit that was published. A similar process should be used for non-Git VCS tools as well. # Tag the current commit GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 git push --tags Annotated tags are preferred because some Git commands ignore unannotated tags if any annotated tags exist. Examples Serde 1.0.0 release notes Serde 0.9.8 release notes Serde 0.9.0 release notes Diesel change log Rustdoc does not show unhelpful implementation details (C-HIDDEN) Rustdoc is supposed to include everything users need to use the crate fully and nothing more. It is fine to explain relevant implementation details in prose but they should not be real entries in the documentation. Especially be selective about which impls are visible in rustdoc -- all the ones that users would need for using the crate fully, but no others. In the following code the rustdoc of PublicError by default would show the From<PrivateError> impl. We choose to hide it with #[doc(hidden)] because users can never have a PrivateError in their code so this impl would never be relevant to them. #![allow(unused)] fn main() { // This error type is returned to users. pub struct PublicError { /* ... */ } // This error type is returned by some private helper functions. struct PrivateError { /* ... */ } // Enable use of `?` operator. #[doc(hidden)] impl From<PrivateError> for PublicError { fn from(err: PrivateError) -> PublicError { /* ... */ } } } pub(crate) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute | Preludes - 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 [names .preludes] Preludes [names .preludes .intro] A prelude is a collection of names that are automatically brought into scope of every module in a crate. These prelude names are not part of the module itself: they are implicitly queried during name resolution . For example, even though something like Box is in scope in every module, you cannot refer to it as self::Box because it is not a member of the current module. [names .preludes .kinds] There are several different preludes: Standard library prelude Extern prelude Language prelude macro_use prelude Tool prelude [names .preludes .std] Standard library prelude [names .preludes .std .intro] Each crate has a standard library prelude, which consists of the names from a single standard library module. [names .preludes .std .module] The module used depends on the crate’s edition, and on whether the no_std attribute is applied to the crate: Edition no_std not applied no_std applied 2015 std::prelude::rust_2015 core::prelude::rust_2015 2018 std::prelude::rust_2018 core::prelude::rust_2018 2021 std::prelude::rust_2021 core::prelude::rust_2021 2024 std::prelude::rust_2024 core::prelude::rust_2024 Note std::prelude::rust_2015 and std::prelude::rust_2018 have the same contents as std::prelude::v1 . core::prelude::rust_2015 and core::prelude::rust_2018 have the same contents as core::prelude::v1 . [names .preludes .extern] Extern prelude [names .preludes .extern .intro] External crates imported with extern crate in the root module or provided to the compiler (as with the --extern flag with rustc ) are added to the extern prelude . If imported with an alias such as extern crate orig_name as new_name , then the symbol new_name is instead added to the prelude. [names .preludes .extern .core] The core crate is always added to the extern prelude. [names .preludes .extern .std] The std crate is added as long as the no_std attribute is not specified in the crate root. [names .preludes .extern .edition2018] 2018 Edition differences In the 2015 edition, crates in the extern prelude cannot be referenced via use declarations , so it is generally standard practice to include extern crate declarations to bring them into scope. Beginning in the 2018 edition, use declarations can reference crates in the extern prelude, so it is considered unidiomatic to use extern crate . Note Additional crates that ship with rustc , such as alloc , and test , are not automatically included with the --extern flag when using Cargo. They must be brought into scope with an extern crate declaration, even in the 2018 edition. #![allow(unused)] fn main() { extern crate alloc; use alloc::rc::Rc; } Cargo does bring in proc_macro to the extern prelude for proc-macro crates only. [names .preludes .extern .no_std] The no_std attribute [names .preludes .extern .no_std .intro] By default, the standard library is automatically included in the crate root module. The std crate is added to the root, along with an implicit macro_use attribute pulling in all macros exported from std into the macro_use prelude . Both core and std are added to the extern prelude . [names .preludes .extern .no_std .allowed-positions] The no_std attribute may be applied at the crate level to prevent the std crate from being automatically added into scope. It does three things: [names .preludes .extern .no_std .extern] Prevents std from being added to the extern prelude . [names .preludes .extern .no_std .module] Affects which module is used to make up the standard library prelude (as described above). [names .preludes .extern .no_std .core] Injects the core crate into the crate root instead of std , and pulls in all macros exported from core in the macro_use prelude . Note Using the core prelude over the standard prelude is useful when either the crate is targeting a platform that does not support the standard library or is purposefully not using the capabilities of the standard library. Those capabilities are mainly dynamic memory allocation (e.g. Box and Vec ) and file and network capabilities (e.g. std::fs and std::io ). Warning Using no_std does not prevent the standard library from being linked in. It is still valid to put extern crate std; into the crate and dependencies can also link it in. [names .preludes .lang] Language prelude [names .preludes .lang .intro] The language prelude includes names of types and attributes that are built-in to the language. The language prelude is always in scope. [names .preludes .lang .entities] It includes the following: Type namespace Boolean type — bool Textual types — char and str Integer types — i8 , i16 , i32 , i64 , i128 , u8 , u16 , u32 , u64 , u128 Machine-dependent integer types — usize and isize floating-point types — f32 and f64 Macro namespace Built-in attributes Built-in derive macros [names .preludes .macro_use] macro_use prelude [names .preludes .macro_use .intro] The macro_use prelude includes macros from external crates that were imported by the macro_use attribute applied to an extern crate . [names .preludes .tool] Tool prelude [names .preludes .tool .intro] The tool prelude includes tool names for external tools in the type namespace . See the tool attributes section for more details. [names .preludes .no_implicit_prelude] The no_implicit_prelude attribute [names .preludes .no_implicit_prelude .intro] The no_implicit_prelude attribute may be applied at the crate level or on a module to indicate that it should not automatically bring the standard library prelude , extern prelude , or tool prelude into scope for that module or any of its descendants. [names .preludes .no_implicit_prelude .lang] This attribute does not affect the language prelude . [names .preludes .no_implicit_prelude .edition2018] 2018 Edition differences In the 2015 edition, the no_implicit_prelude attribute does not affect the macro_use prelude , and all macros exported from the standard library are still included in the macro_use prelude. Starting in the 2018 edition, it will remove the macro_use prelude. | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/documentation.html#prose-contains-hyperlinks-to-relevant-things-c-link | Documentation - 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 Documentation Crate level docs are thorough and include examples (C-CRATE-DOC) See RFC 1687 . All items have a rustdoc example (C-EXAMPLE) Every public module, trait, struct, enum, function, method, macro, and type definition should have an example that exercises the functionality. This guideline should be applied within reason. A link to an applicable example on another item may be sufficient. For example if exactly one function uses a particular type, it may be appropriate to write a single example on either the function or the type and link to it from the other. The purpose of an example is not always to show how to use the item. Readers can be expected to understand how to invoke functions, match on enums, and other fundamental tasks. Rather, an example is often intended to show why someone would want to use the item. // This would be a poor example of using clone(). It mechanically shows *how* to // call clone(), but does nothing to show *why* somebody would want this. fn main() { let hello = "hello"; hello.clone(); } Examples use ? , not try! , not unwrap (C-QUESTION-MARK) Like it or not, example code is often copied verbatim by users. Unwrapping an error should be a conscious decision that the user needs to make. A common way of structuring fallible example code is the following. The lines beginning with # are compiled by cargo test when building the example but will not appear in user-visible rustdoc. /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box<dyn Error>> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` Function docs include error, panic, and safety considerations (C-FAILURE) Error conditions should be documented in an "Errors" section. This applies to trait methods as well -- trait methods for which the implementation is allowed or expected to return an error should be documented with an "Errors" section. For example in the standard library, Some implementations of the std::io::Read::read trait method may return an error. /// Pull some bytes from this source into the specified buffer, returning /// how many bytes were read. /// /// ... lots more info ... /// /// # Errors /// /// If this function encounters any form of I/O or other error, an error /// variant will be returned. If an error is returned then it must be /// guaranteed that no bytes were read. Panic conditions should be documented in a "Panics" section. This applies to trait methods as well -- traits methods for which the implementation is allowed or expected to panic should be documented with a "Panics" section. In the standard library the Vec::insert method may panic. /// Inserts an element at position `index` within the vector, shifting all /// elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. It is not necessary to document all conceivable panic cases, especially if the panic occurs in logic provided by the caller. For example documenting the Display panic in the following code seems excessive. But when in doubt, err on the side of documenting more panic cases. #![allow(unused)] fn main() { /// # Panics /// /// This function panics if `T`'s implementation of `Display` panics. pub fn print<T: Display>(t: T) { println!("{}", t.to_string()); } } Unsafe functions should be documented with a "Safety" section that explains all invariants that the caller is responsible for upholding to use the function correctly. The unsafe std::ptr::read requires the following of the caller. /// Reads the value from `src` without moving it. This leaves the /// memory in `src` unchanged. /// /// # Safety /// /// Beyond accepting a raw pointer, this is unsafe because it semantically /// moves the value out of `src` without preventing further usage of `src`. /// If `T` is not `Copy`, then care must be taken to ensure that the value at /// `src` is not used before the data is overwritten again (e.g. with `write`, /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use /// because it will attempt to drop the value previously at `*src`. /// /// The pointer must be aligned; use `read_unaligned` if that is not the case. Prose contains hyperlinks to relevant things (C-LINK) Regular links can be added inline with the usual markdown syntax of [text](url) . Links to other types can be added by marking them with [`text`] , then adding the link target in a new line at the end of the docstring with [`text`]: <target> , where <target> is described below. Link targets to methods within the same type usually look like this: [`serialize_struct`]: #method.serialize_struct Link targets to other types usually look like this: [`Deserialize`]: trait.Deserialize.html Link targets may also point to a parent or child module: [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html This guideline is officially recommended by RFC 1574 under the heading "Link all the things" . Cargo.toml includes all common metadata (C-METADATA) The [package] section of Cargo.toml should include the following values: authors description license repository keywords categories In addition, there are two optional metadata fields: documentation homepage By default, crates.io links to documentation for the crate on docs.rs . The documentation metadata only needs to be set if the documentation is hosted somewhere other than docs.rs , for example because the crate links against a shared library that is not available in the build environment of docs.rs . The homepage metadata should only be set if there is a unique website for the crate other than the source repository or API documentation. Do not make homepage redundant with either the documentation or repository values. For example, serde sets homepage to https://serde.rs , a dedicated website. Release notes document all significant changes (C-RELNOTES) Users of the crate can read the release notes to find a summary of what changed in each published release of the crate. A link to the release notes, or the notes themselves, should be included in the crate-level documentation and/or the repository linked in Cargo.toml. Breaking changes (as defined in RFC 1105 ) should be clearly identified in the release notes. If using Git to track the source of a crate, every release published to crates.io should have a corresponding tag identifying the commit that was published. A similar process should be used for non-Git VCS tools as well. # Tag the current commit GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 git push --tags Annotated tags are preferred because some Git commands ignore unannotated tags if any annotated tags exist. Examples Serde 1.0.0 release notes Serde 0.9.8 release notes Serde 0.9.0 release notes Diesel change log Rustdoc does not show unhelpful implementation details (C-HIDDEN) Rustdoc is supposed to include everything users need to use the crate fully and nothing more. It is fine to explain relevant implementation details in prose but they should not be real entries in the documentation. Especially be selective about which impls are visible in rustdoc -- all the ones that users would need for using the crate fully, but no others. In the following code the rustdoc of PublicError by default would show the From<PrivateError> impl. We choose to hide it with #[doc(hidden)] because users can never have a PrivateError in their code so this impl would never be relevant to them. #![allow(unused)] fn main() { // This error type is returned to users. pub struct PublicError { /* ... */ } // This error type is returned by some private helper functions. struct PrivateError { /* ... */ } // Enable use of `?` operator. #[doc(hidden)] impl From<PrivateError> for PublicError { fn from(err: PrivateError) -> PublicError { /* ... */ } } } pub(crate) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate. | 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%3DAT2n2ad5edoxiZfbpoMEkNGCapqvjk3Zha8c1DS-IfhWMQRD-QXdRlQEcCYCl1RRAYHR0Mx37s1OKzcyqjS_88yFX-L67y4s2hGhnwpT3j1OIUkQ_EplDVcwoVuogpB-iRktRQbugSbxt_WX | 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://rust-lang.github.io/api-guidelines/macros.html#item-macros-compose-well-with-attributes-c-macro-attr | Macros - 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 Macros Input syntax is evocative of the output (C-EVOCATIVE) Rust macros let you dream up practically whatever input syntax you want. Aim to keep input syntax familiar and cohesive with the rest of your users' code by mirroring existing Rust syntax where possible. Pay attention to the choice and placement of keywords and punctuation. A good guide is to use syntax, especially keywords and punctuation, that is similar to what will be produced in the output of the macro. For example if your macro declares a struct with a particular name given in the input, preface the name with the keyword struct to signal to readers that a struct is being declared with the given name. #![allow(unused)] fn main() { // Prefer this... bitflags! { struct S: u32 { /* ... */ } } // ...over no keyword... bitflags! { S: u32 { /* ... */ } } // ...or some ad-hoc word. bitflags! { flags S: u32 { /* ... */ } } } Another example is semicolons vs commas. Constants in Rust are followed by semicolons so if your macro declares a chain of constants, they should likely be followed by semicolons even if the syntax is otherwise slightly different from Rust's. #![allow(unused)] fn main() { // Ordinary constants use semicolons. const A: u32 = 0b000001; const B: u32 = 0b000010; // So prefer this... bitflags! { struct S: u32 { const C = 0b000100; const D = 0b001000; } } // ...over this. bitflags! { struct S: u32 { const E = 0b010000, const F = 0b100000, } } } Macros are so diverse that these specific examples won't be relevant, but think about how to apply the same principles to your situation. Item macros compose well with attributes (C-MACRO-ATTR) Macros that produce more than one output item should support adding attributes to any one of those items. One common use case would be putting individual items behind a cfg. #![allow(unused)] fn main() { bitflags! { struct Flags: u8 { #[cfg(windows)] const ControlCenter = 0b001; #[cfg(unix)] const Terminal = 0b010; } } } Macros that produce a struct or enum as output should support attributes so that the output can be used with derive. #![allow(unused)] fn main() { bitflags! { #[derive(Default, Serialize)] struct Flags: u8 { const ControlCenter = 0b001; const Terminal = 0b010; } } } Item macros work anywhere that items are allowed (C-ANYWHERE) Rust allows items to be placed at the module level or within a tighter scope like a function. Item macros should work equally well as ordinary items in all of these places. The test suite should include invocations of the macro in at least the module scope and function scope. #![allow(unused)] fn main() { #[cfg(test)] mod tests { test_your_macro_in_a!(module); #[test] fn anywhere() { test_your_macro_in_a!(function); } } } As a simple example of how things can go wrong, this macro works great in a module scope but fails in a function scope. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident :: $t:ident) => { pub struct $t; pub mod $m { pub use super::$t; } } } broken!(m::T); // okay, expands to T and m::T fn g() { broken!(m::U); // fails to compile, super::U refers to the containing module not g } } Item macros support visibility specifiers (C-MACRO-VIS) Follow Rust syntax for visibility of items produced by a macro. Private by default, public if pub is specified. #![allow(unused)] fn main() { bitflags! { struct PrivateFlags: u8 { const A = 0b0001; const B = 0b0010; } } bitflags! { pub struct PublicFlags: u8 { const C = 0b0100; const D = 0b1000; } } } Type fragments are flexible (C-MACRO-TY) If your macro accepts a type fragment like $t:ty in the input, it should be usable with all of the following: Primitives: u8 , &str Relative paths: m::Data Absolute paths: ::base::Data Upward relative paths: super::Data Generics: Vec<String> As a simple example of how things can go wrong, this macro works great with primitives and absolute paths but fails with relative paths. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident => $t:ty) => { pub mod $m { pub struct Wrapper($t); } } } broken!(a => u8); // okay broken!(b => ::std::marker::PhantomData<()>); // okay struct S; broken!(c => S); // fails to compile } | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/std/fmt/trait.Binary.html | Binary in std::fmt - Rust This old browser is unsupported and will most likely display funky things. Binary std 1.92.0 (ded5c06cf 2025-12-08) Binary Sections Examples Required Methods fmt Implementors In std:: fmt std :: fmt Trait Binary Copy item path 1.0.0 · Source pub trait Binary { // Required method fn fmt (&self, f: &mut Formatter <'_>) -> Result < () , Error >; } Expand description b formatting. The Binary trait should format its output as a number in binary. For primitive signed integers ( i8 to i128 , and isize ), negative values are formatted as the two’s complement representation. The alternate flag, # , adds a 0b in front of the output. For more information on formatters, see the module-level documentation . § Examples Basic usage with i32 : let x = 42 ; // 42 is '101010' in binary assert_eq! ( format! ( "{x:b}" ), "101010" ); assert_eq! ( format! ( "{x:#b}" ), "0b101010" ); assert_eq! ( format! ( "{:b}" , - 16 ), "11111111111111111111111111110000" ); Implementing Binary on a type: use std::fmt; struct Length(i32); impl fmt::Binary for Length { fn fmt( & self , f: &mut fmt::Formatter< '_ >) -> fmt::Result { let val = self . 0 ; fmt::Binary::fmt( & val, f) // delegate to i32's implementation } } let l = Length( 107 ); assert_eq! ( format! ( "l as binary is: {l:b}" ), "l as binary is: 1101011" ); assert_eq! ( // Note that the `0b` prefix added by `#` is included in the total width, so we // need to add two to correctly display all 32 bits. format! ( "l as binary is: {l:#034b}" ), "l as binary is: 0b00000000000000000000000001101011" ); Required Methods § 1.0.0 · Source fn fmt (&self, f: &mut Formatter <'_>) -> Result < () , Error > Formats the value using the given formatter. § Errors This function should return Err if, and only if, the provided Formatter returns Err . String formatting is considered an infallible operation; this function only returns a Result because writing to the underlying stream might fail and it must provide a way to propagate the fact that an error has occurred back up the stack. Implementors § 1.0.0 · Source § impl Binary for i8 1.0.0 · Source § impl Binary for i16 1.0.0 · Source § impl Binary for i32 1.0.0 · Source § impl Binary for i64 1.0.0 · Source § impl Binary for i128 1.0.0 · Source § impl Binary for isize 1.0.0 · Source § impl Binary for u8 1.0.0 · Source § impl Binary for u16 1.0.0 · Source § impl Binary for u32 1.0.0 · Source § impl Binary for u64 1.0.0 · Source § impl Binary for u128 1.0.0 · Source § impl Binary for usize 1.0.0 · Source § impl<T> Binary for &T where T: Binary + ? Sized , 1.0.0 · Source § impl<T> Binary for &mut T where T: Binary + ? Sized , 1.28.0 · Source § impl<T> Binary for NonZero <T> where T: ZeroablePrimitive + Binary , 1.74.0 · Source § impl<T> Binary for Saturating <T> where T: Binary , 1.11.0 · Source § impl<T> Binary for Wrapping <T> where T: Binary , | 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/#Comments | 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-logout.html | cargo logout - 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-logout(1) NAME cargo-logout — Remove an API token from the registry locally SYNOPSIS cargo logout [ options ] DESCRIPTION This command will run a credential provider to remove a saved token. For the default cargo:token credential provider, credentials are stored in $CARGO_HOME/credentials.toml where $CARGO_HOME defaults to .cargo in your home directory. If a registry has a credential-provider specified, it will be used. Otherwise, the providers from the config value registry.global-credential-providers will be attempted, starting from the end of the list. If --registry is not specified, then the credentials for the default registry will be removed (configured by registry.default , which defaults to https://crates.io/ ). This will not revoke the token on the server. If you need to revoke the token, visit the registry website and follow its instructions (see https://crates.io/me to revoke the token for https://crates.io/ ). OPTIONS Logout Options --registry registry Name of the registry to use. Registry names are defined in Cargo config files . If not specified, the default registry is used, which is defined by the registry.default config key which defaults to crates-io . 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 Remove the default registry token: cargo logout Remove the token for a specific registry: cargo logout --registry my-registry SEE ALSO cargo(1) , cargo-login(1) | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/macros.html#item-macros-support-visibility-specifiers-c-macro-vis | Macros - 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 Macros Input syntax is evocative of the output (C-EVOCATIVE) Rust macros let you dream up practically whatever input syntax you want. Aim to keep input syntax familiar and cohesive with the rest of your users' code by mirroring existing Rust syntax where possible. Pay attention to the choice and placement of keywords and punctuation. A good guide is to use syntax, especially keywords and punctuation, that is similar to what will be produced in the output of the macro. For example if your macro declares a struct with a particular name given in the input, preface the name with the keyword struct to signal to readers that a struct is being declared with the given name. #![allow(unused)] fn main() { // Prefer this... bitflags! { struct S: u32 { /* ... */ } } // ...over no keyword... bitflags! { S: u32 { /* ... */ } } // ...or some ad-hoc word. bitflags! { flags S: u32 { /* ... */ } } } Another example is semicolons vs commas. Constants in Rust are followed by semicolons so if your macro declares a chain of constants, they should likely be followed by semicolons even if the syntax is otherwise slightly different from Rust's. #![allow(unused)] fn main() { // Ordinary constants use semicolons. const A: u32 = 0b000001; const B: u32 = 0b000010; // So prefer this... bitflags! { struct S: u32 { const C = 0b000100; const D = 0b001000; } } // ...over this. bitflags! { struct S: u32 { const E = 0b010000, const F = 0b100000, } } } Macros are so diverse that these specific examples won't be relevant, but think about how to apply the same principles to your situation. Item macros compose well with attributes (C-MACRO-ATTR) Macros that produce more than one output item should support adding attributes to any one of those items. One common use case would be putting individual items behind a cfg. #![allow(unused)] fn main() { bitflags! { struct Flags: u8 { #[cfg(windows)] const ControlCenter = 0b001; #[cfg(unix)] const Terminal = 0b010; } } } Macros that produce a struct or enum as output should support attributes so that the output can be used with derive. #![allow(unused)] fn main() { bitflags! { #[derive(Default, Serialize)] struct Flags: u8 { const ControlCenter = 0b001; const Terminal = 0b010; } } } Item macros work anywhere that items are allowed (C-ANYWHERE) Rust allows items to be placed at the module level or within a tighter scope like a function. Item macros should work equally well as ordinary items in all of these places. The test suite should include invocations of the macro in at least the module scope and function scope. #![allow(unused)] fn main() { #[cfg(test)] mod tests { test_your_macro_in_a!(module); #[test] fn anywhere() { test_your_macro_in_a!(function); } } } As a simple example of how things can go wrong, this macro works great in a module scope but fails in a function scope. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident :: $t:ident) => { pub struct $t; pub mod $m { pub use super::$t; } } } broken!(m::T); // okay, expands to T and m::T fn g() { broken!(m::U); // fails to compile, super::U refers to the containing module not g } } Item macros support visibility specifiers (C-MACRO-VIS) Follow Rust syntax for visibility of items produced by a macro. Private by default, public if pub is specified. #![allow(unused)] fn main() { bitflags! { struct PrivateFlags: u8 { const A = 0b0001; const B = 0b0010; } } bitflags! { pub struct PublicFlags: u8 { const C = 0b0100; const D = 0b1000; } } } Type fragments are flexible (C-MACRO-TY) If your macro accepts a type fragment like $t:ty in the input, it should be usable with all of the following: Primitives: u8 , &str Relative paths: m::Data Absolute paths: ::base::Data Upward relative paths: super::Data Generics: Vec<String> As a simple example of how things can go wrong, this macro works great with primitives and absolute paths but fails with relative paths. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident => $t:ty) => { pub mod $m { pub struct Wrapper($t); } } } broken!(a => u8); // okay broken!(b => ::std::marker::PhantomData<()>); // okay struct S; broken!(c => S); // fails to compile } | 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%3DAT01G6_nw6Bh-5sCbp2-aSr0g4Qn7kzux3KaClq4B-Ydqu_2cilx63HukRJNrpVSfO5KTOnvI2cAQAO9cOP5vcEy6U8cteIXFwQYm9A31sMi4P1LSY6nof6oJFyCIthvYsIp7MuPsMmVpsdU | 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://rust-lang.github.io/api-guidelines/documentation.html#all-items-have-a-rustdoc-example-c-example | Documentation - 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 Documentation Crate level docs are thorough and include examples (C-CRATE-DOC) See RFC 1687 . All items have a rustdoc example (C-EXAMPLE) Every public module, trait, struct, enum, function, method, macro, and type definition should have an example that exercises the functionality. This guideline should be applied within reason. A link to an applicable example on another item may be sufficient. For example if exactly one function uses a particular type, it may be appropriate to write a single example on either the function or the type and link to it from the other. The purpose of an example is not always to show how to use the item. Readers can be expected to understand how to invoke functions, match on enums, and other fundamental tasks. Rather, an example is often intended to show why someone would want to use the item. // This would be a poor example of using clone(). It mechanically shows *how* to // call clone(), but does nothing to show *why* somebody would want this. fn main() { let hello = "hello"; hello.clone(); } Examples use ? , not try! , not unwrap (C-QUESTION-MARK) Like it or not, example code is often copied verbatim by users. Unwrapping an error should be a conscious decision that the user needs to make. A common way of structuring fallible example code is the following. The lines beginning with # are compiled by cargo test when building the example but will not appear in user-visible rustdoc. /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box<dyn Error>> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` Function docs include error, panic, and safety considerations (C-FAILURE) Error conditions should be documented in an "Errors" section. This applies to trait methods as well -- trait methods for which the implementation is allowed or expected to return an error should be documented with an "Errors" section. For example in the standard library, Some implementations of the std::io::Read::read trait method may return an error. /// Pull some bytes from this source into the specified buffer, returning /// how many bytes were read. /// /// ... lots more info ... /// /// # Errors /// /// If this function encounters any form of I/O or other error, an error /// variant will be returned. If an error is returned then it must be /// guaranteed that no bytes were read. Panic conditions should be documented in a "Panics" section. This applies to trait methods as well -- traits methods for which the implementation is allowed or expected to panic should be documented with a "Panics" section. In the standard library the Vec::insert method may panic. /// Inserts an element at position `index` within the vector, shifting all /// elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. It is not necessary to document all conceivable panic cases, especially if the panic occurs in logic provided by the caller. For example documenting the Display panic in the following code seems excessive. But when in doubt, err on the side of documenting more panic cases. #![allow(unused)] fn main() { /// # Panics /// /// This function panics if `T`'s implementation of `Display` panics. pub fn print<T: Display>(t: T) { println!("{}", t.to_string()); } } Unsafe functions should be documented with a "Safety" section that explains all invariants that the caller is responsible for upholding to use the function correctly. The unsafe std::ptr::read requires the following of the caller. /// Reads the value from `src` without moving it. This leaves the /// memory in `src` unchanged. /// /// # Safety /// /// Beyond accepting a raw pointer, this is unsafe because it semantically /// moves the value out of `src` without preventing further usage of `src`. /// If `T` is not `Copy`, then care must be taken to ensure that the value at /// `src` is not used before the data is overwritten again (e.g. with `write`, /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use /// because it will attempt to drop the value previously at `*src`. /// /// The pointer must be aligned; use `read_unaligned` if that is not the case. Prose contains hyperlinks to relevant things (C-LINK) Regular links can be added inline with the usual markdown syntax of [text](url) . Links to other types can be added by marking them with [`text`] , then adding the link target in a new line at the end of the docstring with [`text`]: <target> , where <target> is described below. Link targets to methods within the same type usually look like this: [`serialize_struct`]: #method.serialize_struct Link targets to other types usually look like this: [`Deserialize`]: trait.Deserialize.html Link targets may also point to a parent or child module: [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html This guideline is officially recommended by RFC 1574 under the heading "Link all the things" . Cargo.toml includes all common metadata (C-METADATA) The [package] section of Cargo.toml should include the following values: authors description license repository keywords categories In addition, there are two optional metadata fields: documentation homepage By default, crates.io links to documentation for the crate on docs.rs . The documentation metadata only needs to be set if the documentation is hosted somewhere other than docs.rs , for example because the crate links against a shared library that is not available in the build environment of docs.rs . The homepage metadata should only be set if there is a unique website for the crate other than the source repository or API documentation. Do not make homepage redundant with either the documentation or repository values. For example, serde sets homepage to https://serde.rs , a dedicated website. Release notes document all significant changes (C-RELNOTES) Users of the crate can read the release notes to find a summary of what changed in each published release of the crate. A link to the release notes, or the notes themselves, should be included in the crate-level documentation and/or the repository linked in Cargo.toml. Breaking changes (as defined in RFC 1105 ) should be clearly identified in the release notes. If using Git to track the source of a crate, every release published to crates.io should have a corresponding tag identifying the commit that was published. A similar process should be used for non-Git VCS tools as well. # Tag the current commit GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 git push --tags Annotated tags are preferred because some Git commands ignore unannotated tags if any annotated tags exist. Examples Serde 1.0.0 release notes Serde 0.9.8 release notes Serde 0.9.0 release notes Diesel change log Rustdoc does not show unhelpful implementation details (C-HIDDEN) Rustdoc is supposed to include everything users need to use the crate fully and nothing more. It is fine to explain relevant implementation details in prose but they should not be real entries in the documentation. Especially be selective about which impls are visible in rustdoc -- all the ones that users would need for using the crate fully, but no others. In the following code the rustdoc of PublicError by default would show the From<PrivateError> impl. We choose to hide it with #[doc(hidden)] because users can never have a PrivateError in their code so this impl would never be relevant to them. #![allow(unused)] fn main() { // This error type is returned to users. pub struct PublicError { /* ... */ } // This error type is returned by some private helper functions. struct PrivateError { /* ... */ } // Enable use of `?` operator. #[doc(hidden)] impl From<PrivateError> for PublicError { fn from(err: PrivateError) -> PublicError { /* ... */ } } } pub(crate) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate. | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/documentation.html#examples-use--not-try-not-unwrap-c-question-mark | Documentation - 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 Documentation Crate level docs are thorough and include examples (C-CRATE-DOC) See RFC 1687 . All items have a rustdoc example (C-EXAMPLE) Every public module, trait, struct, enum, function, method, macro, and type definition should have an example that exercises the functionality. This guideline should be applied within reason. A link to an applicable example on another item may be sufficient. For example if exactly one function uses a particular type, it may be appropriate to write a single example on either the function or the type and link to it from the other. The purpose of an example is not always to show how to use the item. Readers can be expected to understand how to invoke functions, match on enums, and other fundamental tasks. Rather, an example is often intended to show why someone would want to use the item. // This would be a poor example of using clone(). It mechanically shows *how* to // call clone(), but does nothing to show *why* somebody would want this. fn main() { let hello = "hello"; hello.clone(); } Examples use ? , not try! , not unwrap (C-QUESTION-MARK) Like it or not, example code is often copied verbatim by users. Unwrapping an error should be a conscious decision that the user needs to make. A common way of structuring fallible example code is the following. The lines beginning with # are compiled by cargo test when building the example but will not appear in user-visible rustdoc. /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box<dyn Error>> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` Function docs include error, panic, and safety considerations (C-FAILURE) Error conditions should be documented in an "Errors" section. This applies to trait methods as well -- trait methods for which the implementation is allowed or expected to return an error should be documented with an "Errors" section. For example in the standard library, Some implementations of the std::io::Read::read trait method may return an error. /// Pull some bytes from this source into the specified buffer, returning /// how many bytes were read. /// /// ... lots more info ... /// /// # Errors /// /// If this function encounters any form of I/O or other error, an error /// variant will be returned. If an error is returned then it must be /// guaranteed that no bytes were read. Panic conditions should be documented in a "Panics" section. This applies to trait methods as well -- traits methods for which the implementation is allowed or expected to panic should be documented with a "Panics" section. In the standard library the Vec::insert method may panic. /// Inserts an element at position `index` within the vector, shifting all /// elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. It is not necessary to document all conceivable panic cases, especially if the panic occurs in logic provided by the caller. For example documenting the Display panic in the following code seems excessive. But when in doubt, err on the side of documenting more panic cases. #![allow(unused)] fn main() { /// # Panics /// /// This function panics if `T`'s implementation of `Display` panics. pub fn print<T: Display>(t: T) { println!("{}", t.to_string()); } } Unsafe functions should be documented with a "Safety" section that explains all invariants that the caller is responsible for upholding to use the function correctly. The unsafe std::ptr::read requires the following of the caller. /// Reads the value from `src` without moving it. This leaves the /// memory in `src` unchanged. /// /// # Safety /// /// Beyond accepting a raw pointer, this is unsafe because it semantically /// moves the value out of `src` without preventing further usage of `src`. /// If `T` is not `Copy`, then care must be taken to ensure that the value at /// `src` is not used before the data is overwritten again (e.g. with `write`, /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use /// because it will attempt to drop the value previously at `*src`. /// /// The pointer must be aligned; use `read_unaligned` if that is not the case. Prose contains hyperlinks to relevant things (C-LINK) Regular links can be added inline with the usual markdown syntax of [text](url) . Links to other types can be added by marking them with [`text`] , then adding the link target in a new line at the end of the docstring with [`text`]: <target> , where <target> is described below. Link targets to methods within the same type usually look like this: [`serialize_struct`]: #method.serialize_struct Link targets to other types usually look like this: [`Deserialize`]: trait.Deserialize.html Link targets may also point to a parent or child module: [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html This guideline is officially recommended by RFC 1574 under the heading "Link all the things" . Cargo.toml includes all common metadata (C-METADATA) The [package] section of Cargo.toml should include the following values: authors description license repository keywords categories In addition, there are two optional metadata fields: documentation homepage By default, crates.io links to documentation for the crate on docs.rs . The documentation metadata only needs to be set if the documentation is hosted somewhere other than docs.rs , for example because the crate links against a shared library that is not available in the build environment of docs.rs . The homepage metadata should only be set if there is a unique website for the crate other than the source repository or API documentation. Do not make homepage redundant with either the documentation or repository values. For example, serde sets homepage to https://serde.rs , a dedicated website. Release notes document all significant changes (C-RELNOTES) Users of the crate can read the release notes to find a summary of what changed in each published release of the crate. A link to the release notes, or the notes themselves, should be included in the crate-level documentation and/or the repository linked in Cargo.toml. Breaking changes (as defined in RFC 1105 ) should be clearly identified in the release notes. If using Git to track the source of a crate, every release published to crates.io should have a corresponding tag identifying the commit that was published. A similar process should be used for non-Git VCS tools as well. # Tag the current commit GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 git push --tags Annotated tags are preferred because some Git commands ignore unannotated tags if any annotated tags exist. Examples Serde 1.0.0 release notes Serde 0.9.8 release notes Serde 0.9.0 release notes Diesel change log Rustdoc does not show unhelpful implementation details (C-HIDDEN) Rustdoc is supposed to include everything users need to use the crate fully and nothing more. It is fine to explain relevant implementation details in prose but they should not be real entries in the documentation. Especially be selective about which impls are visible in rustdoc -- all the ones that users would need for using the crate fully, but no others. In the following code the rustdoc of PublicError by default would show the From<PrivateError> impl. We choose to hide it with #[doc(hidden)] because users can never have a PrivateError in their code so this impl would never be relevant to them. #![allow(unused)] fn main() { // This error type is returned to users. pub struct PublicError { /* ... */ } // This error type is returned by some private helper functions. struct PrivateError { /* ... */ } // Enable use of `?` operator. #[doc(hidden)] impl From<PrivateError> for PublicError { fn from(err: PrivateError) -> PublicError { /* ... */ } } } pub(crate) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate. | 2026-01-13T09:29:13 |
https://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b51-purpose | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/attributes.html#r-attributes.allowed-position | 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://rust-lang.github.io/api-guidelines/macros.html#item-macros-work-anywhere-that-items-are-allowed-c-anywhere | Macros - 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 Macros Input syntax is evocative of the output (C-EVOCATIVE) Rust macros let you dream up practically whatever input syntax you want. Aim to keep input syntax familiar and cohesive with the rest of your users' code by mirroring existing Rust syntax where possible. Pay attention to the choice and placement of keywords and punctuation. A good guide is to use syntax, especially keywords and punctuation, that is similar to what will be produced in the output of the macro. For example if your macro declares a struct with a particular name given in the input, preface the name with the keyword struct to signal to readers that a struct is being declared with the given name. #![allow(unused)] fn main() { // Prefer this... bitflags! { struct S: u32 { /* ... */ } } // ...over no keyword... bitflags! { S: u32 { /* ... */ } } // ...or some ad-hoc word. bitflags! { flags S: u32 { /* ... */ } } } Another example is semicolons vs commas. Constants in Rust are followed by semicolons so if your macro declares a chain of constants, they should likely be followed by semicolons even if the syntax is otherwise slightly different from Rust's. #![allow(unused)] fn main() { // Ordinary constants use semicolons. const A: u32 = 0b000001; const B: u32 = 0b000010; // So prefer this... bitflags! { struct S: u32 { const C = 0b000100; const D = 0b001000; } } // ...over this. bitflags! { struct S: u32 { const E = 0b010000, const F = 0b100000, } } } Macros are so diverse that these specific examples won't be relevant, but think about how to apply the same principles to your situation. Item macros compose well with attributes (C-MACRO-ATTR) Macros that produce more than one output item should support adding attributes to any one of those items. One common use case would be putting individual items behind a cfg. #![allow(unused)] fn main() { bitflags! { struct Flags: u8 { #[cfg(windows)] const ControlCenter = 0b001; #[cfg(unix)] const Terminal = 0b010; } } } Macros that produce a struct or enum as output should support attributes so that the output can be used with derive. #![allow(unused)] fn main() { bitflags! { #[derive(Default, Serialize)] struct Flags: u8 { const ControlCenter = 0b001; const Terminal = 0b010; } } } Item macros work anywhere that items are allowed (C-ANYWHERE) Rust allows items to be placed at the module level or within a tighter scope like a function. Item macros should work equally well as ordinary items in all of these places. The test suite should include invocations of the macro in at least the module scope and function scope. #![allow(unused)] fn main() { #[cfg(test)] mod tests { test_your_macro_in_a!(module); #[test] fn anywhere() { test_your_macro_in_a!(function); } } } As a simple example of how things can go wrong, this macro works great in a module scope but fails in a function scope. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident :: $t:ident) => { pub struct $t; pub mod $m { pub use super::$t; } } } broken!(m::T); // okay, expands to T and m::T fn g() { broken!(m::U); // fails to compile, super::U refers to the containing module not g } } Item macros support visibility specifiers (C-MACRO-VIS) Follow Rust syntax for visibility of items produced by a macro. Private by default, public if pub is specified. #![allow(unused)] fn main() { bitflags! { struct PrivateFlags: u8 { const A = 0b0001; const B = 0b0010; } } bitflags! { pub struct PublicFlags: u8 { const C = 0b0100; const D = 0b1000; } } } Type fragments are flexible (C-MACRO-TY) If your macro accepts a type fragment like $t:ty in the input, it should be usable with all of the following: Primitives: u8 , &str Relative paths: m::Data Absolute paths: ::base::Data Upward relative paths: super::Data Generics: Vec<String> As a simple example of how things can go wrong, this macro works great with primitives and absolute paths but fails with relative paths. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident => $t:ty) => { pub mod $m { pub struct Wrapper($t); } } } broken!(a => u8); // okay broken!(b => ::std::marker::PhantomData<()>); // okay struct S; broken!(c => S); // fails to compile } | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/documentation.html#function-docs-include-error-panic-and-safety-considerations-c-failure | Documentation - 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 Documentation Crate level docs are thorough and include examples (C-CRATE-DOC) See RFC 1687 . All items have a rustdoc example (C-EXAMPLE) Every public module, trait, struct, enum, function, method, macro, and type definition should have an example that exercises the functionality. This guideline should be applied within reason. A link to an applicable example on another item may be sufficient. For example if exactly one function uses a particular type, it may be appropriate to write a single example on either the function or the type and link to it from the other. The purpose of an example is not always to show how to use the item. Readers can be expected to understand how to invoke functions, match on enums, and other fundamental tasks. Rather, an example is often intended to show why someone would want to use the item. // This would be a poor example of using clone(). It mechanically shows *how* to // call clone(), but does nothing to show *why* somebody would want this. fn main() { let hello = "hello"; hello.clone(); } Examples use ? , not try! , not unwrap (C-QUESTION-MARK) Like it or not, example code is often copied verbatim by users. Unwrapping an error should be a conscious decision that the user needs to make. A common way of structuring fallible example code is the following. The lines beginning with # are compiled by cargo test when building the example but will not appear in user-visible rustdoc. /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box<dyn Error>> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` Function docs include error, panic, and safety considerations (C-FAILURE) Error conditions should be documented in an "Errors" section. This applies to trait methods as well -- trait methods for which the implementation is allowed or expected to return an error should be documented with an "Errors" section. For example in the standard library, Some implementations of the std::io::Read::read trait method may return an error. /// Pull some bytes from this source into the specified buffer, returning /// how many bytes were read. /// /// ... lots more info ... /// /// # Errors /// /// If this function encounters any form of I/O or other error, an error /// variant will be returned. If an error is returned then it must be /// guaranteed that no bytes were read. Panic conditions should be documented in a "Panics" section. This applies to trait methods as well -- traits methods for which the implementation is allowed or expected to panic should be documented with a "Panics" section. In the standard library the Vec::insert method may panic. /// Inserts an element at position `index` within the vector, shifting all /// elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. It is not necessary to document all conceivable panic cases, especially if the panic occurs in logic provided by the caller. For example documenting the Display panic in the following code seems excessive. But when in doubt, err on the side of documenting more panic cases. #![allow(unused)] fn main() { /// # Panics /// /// This function panics if `T`'s implementation of `Display` panics. pub fn print<T: Display>(t: T) { println!("{}", t.to_string()); } } Unsafe functions should be documented with a "Safety" section that explains all invariants that the caller is responsible for upholding to use the function correctly. The unsafe std::ptr::read requires the following of the caller. /// Reads the value from `src` without moving it. This leaves the /// memory in `src` unchanged. /// /// # Safety /// /// Beyond accepting a raw pointer, this is unsafe because it semantically /// moves the value out of `src` without preventing further usage of `src`. /// If `T` is not `Copy`, then care must be taken to ensure that the value at /// `src` is not used before the data is overwritten again (e.g. with `write`, /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use /// because it will attempt to drop the value previously at `*src`. /// /// The pointer must be aligned; use `read_unaligned` if that is not the case. Prose contains hyperlinks to relevant things (C-LINK) Regular links can be added inline with the usual markdown syntax of [text](url) . Links to other types can be added by marking them with [`text`] , then adding the link target in a new line at the end of the docstring with [`text`]: <target> , where <target> is described below. Link targets to methods within the same type usually look like this: [`serialize_struct`]: #method.serialize_struct Link targets to other types usually look like this: [`Deserialize`]: trait.Deserialize.html Link targets may also point to a parent or child module: [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html This guideline is officially recommended by RFC 1574 under the heading "Link all the things" . Cargo.toml includes all common metadata (C-METADATA) The [package] section of Cargo.toml should include the following values: authors description license repository keywords categories In addition, there are two optional metadata fields: documentation homepage By default, crates.io links to documentation for the crate on docs.rs . The documentation metadata only needs to be set if the documentation is hosted somewhere other than docs.rs , for example because the crate links against a shared library that is not available in the build environment of docs.rs . The homepage metadata should only be set if there is a unique website for the crate other than the source repository or API documentation. Do not make homepage redundant with either the documentation or repository values. For example, serde sets homepage to https://serde.rs , a dedicated website. Release notes document all significant changes (C-RELNOTES) Users of the crate can read the release notes to find a summary of what changed in each published release of the crate. A link to the release notes, or the notes themselves, should be included in the crate-level documentation and/or the repository linked in Cargo.toml. Breaking changes (as defined in RFC 1105 ) should be clearly identified in the release notes. If using Git to track the source of a crate, every release published to crates.io should have a corresponding tag identifying the commit that was published. A similar process should be used for non-Git VCS tools as well. # Tag the current commit GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 git push --tags Annotated tags are preferred because some Git commands ignore unannotated tags if any annotated tags exist. Examples Serde 1.0.0 release notes Serde 0.9.8 release notes Serde 0.9.0 release notes Diesel change log Rustdoc does not show unhelpful implementation details (C-HIDDEN) Rustdoc is supposed to include everything users need to use the crate fully and nothing more. It is fine to explain relevant implementation details in prose but they should not be real entries in the documentation. Especially be selective about which impls are visible in rustdoc -- all the ones that users would need for using the crate fully, but no others. In the following code the rustdoc of PublicError by default would show the From<PrivateError> impl. We choose to hide it with #[doc(hidden)] because users can never have a PrivateError in their code so this impl would never be relevant to them. #![allow(unused)] fn main() { // This error type is returned to users. pub struct PublicError { /* ... */ } // This error type is returned by some private helper functions. struct PrivateError { /* ... */ } // Enable use of `?` operator. #[doc(hidden)] impl From<PrivateError> for PublicError { fn from(err: PrivateError) -> PublicError { /* ... */ } } } pub(crate) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate. | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/macros.html#type-fragments-are-flexible-c-macro-ty | Macros - 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 Macros Input syntax is evocative of the output (C-EVOCATIVE) Rust macros let you dream up practically whatever input syntax you want. Aim to keep input syntax familiar and cohesive with the rest of your users' code by mirroring existing Rust syntax where possible. Pay attention to the choice and placement of keywords and punctuation. A good guide is to use syntax, especially keywords and punctuation, that is similar to what will be produced in the output of the macro. For example if your macro declares a struct with a particular name given in the input, preface the name with the keyword struct to signal to readers that a struct is being declared with the given name. #![allow(unused)] fn main() { // Prefer this... bitflags! { struct S: u32 { /* ... */ } } // ...over no keyword... bitflags! { S: u32 { /* ... */ } } // ...or some ad-hoc word. bitflags! { flags S: u32 { /* ... */ } } } Another example is semicolons vs commas. Constants in Rust are followed by semicolons so if your macro declares a chain of constants, they should likely be followed by semicolons even if the syntax is otherwise slightly different from Rust's. #![allow(unused)] fn main() { // Ordinary constants use semicolons. const A: u32 = 0b000001; const B: u32 = 0b000010; // So prefer this... bitflags! { struct S: u32 { const C = 0b000100; const D = 0b001000; } } // ...over this. bitflags! { struct S: u32 { const E = 0b010000, const F = 0b100000, } } } Macros are so diverse that these specific examples won't be relevant, but think about how to apply the same principles to your situation. Item macros compose well with attributes (C-MACRO-ATTR) Macros that produce more than one output item should support adding attributes to any one of those items. One common use case would be putting individual items behind a cfg. #![allow(unused)] fn main() { bitflags! { struct Flags: u8 { #[cfg(windows)] const ControlCenter = 0b001; #[cfg(unix)] const Terminal = 0b010; } } } Macros that produce a struct or enum as output should support attributes so that the output can be used with derive. #![allow(unused)] fn main() { bitflags! { #[derive(Default, Serialize)] struct Flags: u8 { const ControlCenter = 0b001; const Terminal = 0b010; } } } Item macros work anywhere that items are allowed (C-ANYWHERE) Rust allows items to be placed at the module level or within a tighter scope like a function. Item macros should work equally well as ordinary items in all of these places. The test suite should include invocations of the macro in at least the module scope and function scope. #![allow(unused)] fn main() { #[cfg(test)] mod tests { test_your_macro_in_a!(module); #[test] fn anywhere() { test_your_macro_in_a!(function); } } } As a simple example of how things can go wrong, this macro works great in a module scope but fails in a function scope. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident :: $t:ident) => { pub struct $t; pub mod $m { pub use super::$t; } } } broken!(m::T); // okay, expands to T and m::T fn g() { broken!(m::U); // fails to compile, super::U refers to the containing module not g } } Item macros support visibility specifiers (C-MACRO-VIS) Follow Rust syntax for visibility of items produced by a macro. Private by default, public if pub is specified. #![allow(unused)] fn main() { bitflags! { struct PrivateFlags: u8 { const A = 0b0001; const B = 0b0010; } } bitflags! { pub struct PublicFlags: u8 { const C = 0b0100; const D = 0b1000; } } } Type fragments are flexible (C-MACRO-TY) If your macro accepts a type fragment like $t:ty in the input, it should be usable with all of the following: Primitives: u8 , &str Relative paths: m::Data Absolute paths: ::base::Data Upward relative paths: super::Data Generics: Vec<String> As a simple example of how things can go wrong, this macro works great with primitives and absolute paths but fails with relative paths. #![allow(unused)] fn main() { macro_rules! broken { ($m:ident => $t:ty) => { pub mod $m { pub struct Wrapper($t); } } } broken!(a => u8); // okay broken!(b => ::std::marker::PhantomData<()>); // okay struct S; broken!(c => S); // fails to compile } | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/commands/cargo-pkgid.html | cargo pkgid - 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-pkgid(1) NAME cargo-pkgid — Print a fully qualified package specification SYNOPSIS cargo pkgid [ options ] [ spec ] DESCRIPTION Given a spec argument, print out the fully qualified package ID specifier for a package or dependency in the current workspace. This command will generate an error if spec is ambiguous as to which package it refers to in the dependency graph. If no spec is given, then the specifier for the local package is printed. This command requires that a lockfile is available and dependencies have been fetched. A package specifier consists of a name, version, and source URL. You are allowed to use partial specifiers to succinctly match a specific package as long as it matches only one package. This specifier is also used by other parts in Cargo, such as cargo-metadata(1) and JSON messages emitted by Cargo. The format of a spec can be one of the following: SPEC Structure Example SPEC name bitflags name @ version bitflags@1.0.4 url https://github.com/rust-lang/cargo url # version https://github.com/rust-lang/cargo#0.33.0 url # name https://github.com/rust-lang/crates.io-index#bitflags url # name @ version https://github.com/rust-lang/cargo#crates-io@0.21.0 The specification grammar can be found in chapter Package ID Specifications . OPTIONS Package Selection -p spec --package spec Get the package ID for the given package instead of the current package. 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 Retrieve package specification for foo package: cargo pkgid foo Retrieve package specification for version 1.0.0 of foo : cargo pkgid foo@1.0.0 Retrieve package specification for foo from crates.io: cargo pkgid https://github.com/rust-lang/crates.io-index#foo Retrieve package specification for foo from a local package: cargo pkgid file:///path/to/local/package#foo SEE ALSO cargo(1) , cargo-generate-lockfile(1) , cargo-metadata(1) , Package ID Specifications , JSON messages | 2026-01-13T09:29:13 |
https://spdx.github.io/spdx-spec/v2.3/license-matching-guidelines-and-templates/#b22-guideline-official-license-headers | Annex B: License Matching Guidelines and Templates - SPDX Specification 2.3.0 SPDX Specification 2.3.0 Copyright Introduction Clause 1: Scope Clause 2: Normative references Clause 3: Terms and definitions Clause 4: Conformance Clause 5: Composition of an SPDX document Clause 6: Document Creation Information Clause 7: Package Information Clause 8: File Information Clause 9: Snippet Information Clause 10: Other Licensing Information Detected Clause 11: Relationship between SPDX Elements Information Clause 12: Annotation Information Clause 13: Review Information (deprecated) Annex A: SPDX License List Annex B: License Matching Guidelines and Templates B.1 SPDX license list matching guidelines B.2 How these guidelines are applied B.2.1 Purpose B.2.2 Guideline: official license headers B.3 Substantive text B.3.1 Purpose B.3.2 Guideline: verbatim text B.3.3 Guideline: no additional text B.3.4 Guideline: replaceable text B.3.5 Guideline: omittable text B.4 Whitespace B.4.1 Purpose B.4.2 Guideline B.5 Capitalization B.5.1 Purpose B.5.2 Guideline B.6 Punctuation B.6.1 Purpose B.6.2 Guideline: punctuation B.6.3 Guideline: hyphens, dashes B.6.4 Guideline: Quotes B.7 Code Comment Indicators B.7.1 Purpose B.7.2 Guideline B.8 Bullets and numbering B.8.1 Purpose B.8.2 Guideline B.9 Varietal word spelling B.9.1 Purpose B.9.2 Guideline B.10 Copyright symbol B.10.1 Purpose B.10.2 Guideline B.11 Copyright notice B.11.1 Purpose B.11.2 Guideline B.12 License name or title B.12.1 Purpose B.12.2 Guideline B.13 Extraneous text at the end of a license B.13.1 Purpose B.13.2 Guideline B.14 HTTP Protocol B.14.1 Purpose B.14.2 Guideline B.15 SPDX License list B.15.1 Template access B.15.2 License List XML format B.15.3 Legacy Text Template format Annex C: RDF Object Model and Identifier Syntax Annex D: SPDX License Expressions Annex E: Using SPDX short identifiers in Source Files Annex F: External Repository Identifiers Annex G: SPDX Lite Annex H: SPDX File Tags Annex I: Differences from Earlier SPDX Versions Annex J: Creative Commons Attribution License 3.0 Unported Annex K: How To Use SPDX in Different Scenarios Bibliography SPDX Specification 2.3.0 Annex B: License Matching Guidelines and Templates Annex B License matching guidelines and templates (Informative) B.1 SPDX license list matching guidelines The SPDX License List Matching Guidelines provide guidelines to be used for the purposes of matching licenses and license exceptions against those included on the SPDX License List. There is no intent here to make a judgment or interpretation, but merely to ensure that when one SPDX user identifies a license as "BSD-3-Clause," for example, it is indeed the same license as what someone else identifies as "BSD-3-Clause" and the same license as what is listed on the SPDX License List. As noted here, some of the matching guidelines are implemented in the XML files of the SPDX License List repository. B.2 How these guidelines are applied B.2.1 Purpose To ensure consistent results by different SPDX document creators when matching license information that will be included in the License Information in File field. SPDX document creators or tools may match on the license or exception text itself, the official license header, or the SPDX License List short identifier. B.2.2 Guideline: official license headers The matching guidelines apply to license and exception text, as well as official license headers. Official license headers are defined by the SPDX License List as specific text specified within the license itself to be put in the header of files. (see explanation of SPDX License List fields for more info). The following XML tag is used to implement this guideline: <standardLicenseHeader> B.3 Substantive text B.3.1 Purpose To ensure that when matching licenses and exceptions to the SPDX License List, there is an appropriate balance between matching against the substantive text and disregarding parts of the text that do not alter the substantive text or legal meaning. Further guidelines of what can be disregarded or considered replaceable for purposes of matching are listed below here and in the subsequent specific guidelines. A conservative approach is taken in regard to rules relating to disregarded or replaceable text. B.3.2 Guideline: verbatim text License and exception text should be the same verbatim text (except for the guidelines stated here). The text should be in the same order, e.g., differently ordered paragraphs would not be considered a match. B.3.3 Guideline: no additional text Matched text should only include that found in the vetted license or exception text. Where a license or exception found includes additional text or clauses, this should not be considered a match. B.3.4 Guideline: replaceable text Some licenses include text that refers to the specific copyright holder or author, yet the rest of the license is exactly the same. The intent here is to avoid the inclusion of a specific name in one part of the license resulting in a non-match where the license is otherwise an exact match to the legally substantive terms (e.g., the third clause and disclaimer in the BSD licenses, or the third, fourth, and fifth clauses of Apache-1.1). In these cases, there should be a positive license match. The text indicated as such can be replaced with similar values (e.g., a different name or generic term; different date) and still be considered a positive match. This rule also applies to text-matching in official license headers (see Guideline: official license headers). The following XML tag is used to implement this guideline. <alt> with 2 attributes: match - a POSIX extended regular expression (ERE) to match the replaceable text name - an identifier for the variable text unique to the license XML document The original text is enclosed within the beginning and ending alt tags. For example: <alt match="(?i:copyright.{0,200})." name="copyright1">Copyright Linux Foundation</alt> The original replaceable text appears on the SPDX License List webpage in red text. B.3.5 Guideline: omittable text Some licenses have text that can simply be ignored. The intent here is to avoid the inclusion of certain text that is superfluous or irrelevant in regards to the substantive license text resulting in a non-match where the license is otherwise an exact match (e.g., directions on how to apply the license or other similar exhibits). In these cases, there should be a positive license match. The license should be considered a match if the text indicated is present and matches OR the text indicated is missing altogether. The following XML tag is used to implement this guideline: <optional> For example: <optional>Apache License Version 2.0, January 2004 http://www.apache.org/licenses/</optional> Omittable text appears on the SPDX License List webpage in blue text. B.4 Whitespace B.4.1 Purpose To avoid the possibility of a non-match due to different spacing of words, line breaks, or paragraphs. B.4.2 Guideline All whitespace should be treated as a single blank space. XML files do not require specific markup to implement this guideline. B.5 Capitalization B.5.1 Purpose To avoid the possibility of a non-match due to lowercase or uppercase letters in otherwise the same words. B.5.2 Guideline All uppercase and lowercase letters should be treated as lowercase letters. XML files do not require specific markup to implement this guideline. B.6 Punctuation B.6.1 Purpose Because punctuation can change the meaning of a sentence, punctuation needs to be included in the matching process. XML files do not require specific markup to implement this guideline. B.6.2 Guideline: punctuation Punctuation should be matched, unless otherwise stated in these guidelines. B.6.3 Guideline: hyphens, dashes Any hyphen, dash, en dash, em dash, or other variation should be considered equivalent. B.6.4 Guideline: Quotes Any variation of quotations (single, double, curly, etc.) should be considered equivalent. B.7 Code Comment Indicators B.7.1 Purpose To avoid the possibility of a non-match due to the existence or absence of code comment indicators placed within the license text, e.g. at the start of each line of text. B.7.2 Guideline Any kind of code comment indicator or prefix which occurs at the beginning of each line in a matchable section should be ignored for matching purposes. XML files do not require specific markup to implement this guideline. B.8 Bullets and numbering B.8.1 Purpose To avoid the possibility of a non-match due to the otherwise same license using bullets instead of numbers, number instead of letter, or no bullets instead of bullet, etc., for a list of clauses. B.8.2 Guideline Where a line starts with a bullet, number, letter, or some form of a list item (determined where list item is followed by a space, then the text of the sentence), ignore the list item for matching purposes. The following XML tag is used to implement this guideline: <bullet> For example: <bullet>1.0</bullet> B.9 Varietal word spelling B.9.1 Purpose English uses different spelling for some words. By identifying the spelling variations for words found or likely to be found in licenses, we avoid the possibility of a non-match due to the same word being spelled differently. This list is not meant to be an exhaustive list of all spelling variations, but meant to capture the words most likely to be found in open source software licenses. B.9.2 Guideline The words in each line of the text file available at https://spdx.org/licenses/equivalentwords.txt are considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. B.10 Copyright symbol B.10.1 Purpose By having a rule regarding the use of "©", "(c)", or "copyright", we avoid the possibility of a mismatch based on these variations. B.10.2 Guideline "©", "(c)", or "Copyright" should be considered equivalent and interchangeable. XML files do not require specific markup to implement this guideline. The copyright symbol is part of the copyright notice, see implementation of that guideline below. B.11 Copyright notice B.11.1 Purpose To avoid a license mismatch merely because the copyright notice (usually found above the actual license or exception text) is different. The copyright notice is important information to be recorded elsewhere in the SPDX document, but for the purposes of matching a license to the SPDX License List, it should be ignored because it is not part of the substantive license text. B.11.2 Guideline Ignore copyright notices. A copyright notice consists of the following elements, for example: "2012 Copyright, John Doe. All rights reserved." or "(c) 2012 John Doe." The following XML tag is used to implement this guideline: <copyrightText> For example: <copyrightText>Copyright 2022 Linux Foundation</copyrightText> B.12 License name or title B.12.1 Purpose To avoid a license mismatch merely because the name or title of the license is different than how the license is usually referred to or different than the SPDX full name. This also avoids a mismatch if the title or name of the license is simply not included. B.12.2 Guideline Ignore the license name or title for matching purposes, so long as what ignored is the title only and there is no additional substantive text added here. The following XML tag is used to implement this guideline: <titleText> For example: <titleText>Attribution Assurance License</titleText> B.13 Extraneous text at the end of a license B.13.1 Purpose To avoid a license mismatch merely because extraneous text that appears at the end of the terms of a license is different or missing. This also avoids a mismatch if the extraneous text merely serves as a license notice example and includes a specific copyright holder's name. B.13.2 Guideline Ignore any text that occurs after the obvious end of the license and does not include substantive text of the license, for example: text that occurs after a statement such as, "END OF TERMS AND CONDITIONS," or an exhibit or appendix that includes an example or instructions on to how to apply the license to your code. Do not apply this guideline or ignore text that is comprised of additional license terms (e.g., permitted additional terms under GPL-3.0, section 7). To implement this guideline, use the <optional> XML element tag as described in section B.3.5. B.14 HTTP Protocol B.14.1 Purpose To avoid a license mismatch due to a difference in a hyperlink protocol (e.g. http vs. https). B.14.2 Guideline HTTP:// and HTTPS:// should be considered equivalent. XML files do not require specific markup to implement this guideline. B.15 SPDX License list B.15.1 Template access The license XML can be accessed in the license-list-data repository under the license-list-XML directory. Although the license list XML files can also be found in the license-list-XML repo, users are encouraged to use the published versions in the license-list-data repository. The license-list-data repository is tagged by release. Only tagged released versions of the license list are considered stable. B.15.2 License List XML format A full schema for the License List XML can be found at https://github.com/spdx/license-list-XML/blob/master/schema/ListedLicense.xsd. B.15.3 Legacy Text Template format Prior to the XML format, a text template was used to express variable and optional text in licenses. This text template is still supported, however, users are encouraged to use the more expressive XML format. A legacy template is composed of text with zero or more rules embedded in it. A rule is a variable section of a license wrapped between double angle brackets “\<\<>>” and is composed of 4 fields. Each field is separated with a semi-colon “;”. Rules cannot be embedded within other rules. Rule fields begin with a case sensitive tag followed by an equal sign “=”. Rule fields: type: indicates whether the text is replaceable or omittable as per Matching Guideline #2 (“Substantive Text”). Indicated by <<var; . . . >> or... Indicated by <<beginOptional; . . .>> and <<endOptional>> respectively. This field is the first field and is required. name: name of the field in the template. This field is unique within each license template. This field is required. original: the original text of the rule. This field is required for a rule type: <<var; . . . >> match: a POSIX extended regular expression (ERE). This field is required for a rule type: <<var; . . . >> The POSIX ERE in the match field has the following restrictions and extensions: Semicolons are escaped with \; POSIX Bracket Extensions are not allowed EXAMPLE: <<var;name=organizationClause3;original=the copyright holder;match=.+>> Previous Next Copyright © 2010 - 2022 Linux Foundation and its Contributors. Built with MkDocs using a theme provided by Read the Docs . « Previous Next » | 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%3DAT2n2ad5edoxiZfbpoMEkNGCapqvjk3Zha8c1DS-IfhWMQRD-QXdRlQEcCYCl1RRAYHR0Mx37s1OKzcyqjS_88yFX-L67y4s2hGhnwpT3j1OIUkQ_EplDVcwoVuogpB-iRktRQbugSbxt_WX | 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/types/function-pointer.html | Function pointer types - 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 [type .fn-pointer] Function pointer types [type .fn-pointer .syntax] Syntax BareFunctionType → ForLifetimes ? FunctionTypeQualifiers fn ( FunctionParametersMaybeNamedVariadic ? ) BareFunctionReturnType ? FunctionTypeQualifiers → unsafe ? ( extern Abi ? ) ? BareFunctionReturnType → -> TypeNoBounds FunctionParametersMaybeNamedVariadic → MaybeNamedFunctionParameters | MaybeNamedFunctionParametersVariadic MaybeNamedFunctionParameters → MaybeNamedParam ( , MaybeNamedParam ) * , ? MaybeNamedParam → OuterAttribute * ( ( IDENTIFIER | _ ) : ) ? Type MaybeNamedFunctionParametersVariadic → ( MaybeNamedParam , ) * MaybeNamedParam , OuterAttribute * ... Show Railroad BareFunctionType ForLifetimes FunctionTypeQualifiers fn ( FunctionParametersMaybeNamedVariadic ) BareFunctionReturnType FunctionTypeQualifiers unsafe extern Abi BareFunctionReturnType -> TypeNoBounds FunctionParametersMaybeNamedVariadic MaybeNamedFunctionParameters MaybeNamedFunctionParametersVariadic MaybeNamedFunctionParameters MaybeNamedParam , MaybeNamedParam , MaybeNamedParam OuterAttribute IDENTIFIER _ : Type MaybeNamedFunctionParametersVariadic MaybeNamedParam , MaybeNamedParam , OuterAttribute ... [type .fn-pointer .intro] Function pointer types, written using the fn keyword, refer to a function whose identity is not necessarily known at compile-time. An example where Binop is defined as a function pointer type: #![allow(unused)] fn main() { fn add(x: i32, y: i32) -> i32 { x + y } let mut x = add(5,7); type Binop = fn(i32, i32) -> i32; let bo: Binop = add; x = bo(5,7); } [type .fn-pointer .coercion] Function pointers can be created via a coercion from both function items and non-capturing, non-async closures . [type .fn-pointer .qualifiers] The unsafe qualifier indicates that the type’s value is an unsafe function , and the extern qualifier indicates it is an extern function . [type .fn-pointer .constraint-variadic] For the function to be variadic, its extern ABI must be one of those listed in items.extern.variadic.conventions . [type .fn-pointer .attributes] Attributes on function pointer parameters Attributes on function pointer parameters follow the same rules and restrictions as regular function parameters . | 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%3DAT01G6_nw6Bh-5sCbp2-aSr0g4Qn7kzux3KaClq4B-Ydqu_2cilx63HukRJNrpVSfO5KTOnvI2cAQAO9cOP5vcEy6U8cteIXFwQYm9A31sMi4P1LSY6nof6oJFyCIthvYsIp7MuPsMmVpsdU | 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://ko-kr.facebook.com/reg/?entry_point=login&amp%3Bnext=https%3A%2F%2Fwww.facebook.com%2Fshare_channel%2F%3Ftype%3Dreshare%26link%3Dhttps%253A%252F%252Fdev.to%252Ftauri%252Ftauri-10-release-candidate-53jk%26app_id%3D966242223397117%26source_surface%3Dexternal_reshare%26display%26hashtag | 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://vi-vn.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT3JYaROIHDRnGnvxRuIozFF_BGGvvoNi8kVPWnSK0yCW2_Va2rKJWNXZ3PUqk5CKpNtOfbF-WNUpIWc7WVvePlsk9n9z3ptr24Okxk2028tZW0HuZ3QVvGoPKfc7Ts55I89ELD7U7OWf7bu | 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/std/fmt/trait.Octal.html | Octal in std::fmt - Rust This old browser is unsupported and will most likely display funky things. Octal std 1.92.0 (ded5c06cf 2025-12-08) Octal Sections Examples Required Methods fmt Implementors In std:: fmt std :: fmt Trait Octal Copy item path 1.0.0 · Source pub trait Octal { // Required method fn fmt (&self, f: &mut Formatter <'_>) -> Result < () , Error >; } Expand description o formatting. The Octal trait should format its output as a number in base-8. For primitive signed integers ( i8 to i128 , and isize ), negative values are formatted as the two’s complement representation. The alternate flag, # , adds a 0o in front of the output. For more information on formatters, see the module-level documentation . § Examples Basic usage with i32 : let x = 42 ; // 42 is '52' in octal assert_eq! ( format! ( "{x:o}" ), "52" ); assert_eq! ( format! ( "{x:#o}" ), "0o52" ); assert_eq! ( format! ( "{:o}" , - 16 ), "37777777760" ); Implementing Octal on a type: use std::fmt; struct Length(i32); impl fmt::Octal for Length { fn fmt( & self , f: &mut fmt::Formatter< '_ >) -> fmt::Result { let val = self . 0 ; fmt::Octal::fmt( & val, f) // delegate to i32's implementation } } let l = Length( 9 ); assert_eq! ( format! ( "l as octal is: {l:o}" ), "l as octal is: 11" ); assert_eq! ( format! ( "l as octal is: {l:#06o}" ), "l as octal is: 0o0011" ); Required Methods § 1.0.0 · Source fn fmt (&self, f: &mut Formatter <'_>) -> Result < () , Error > Formats the value using the given formatter. § Errors This function should return Err if, and only if, the provided Formatter returns Err . String formatting is considered an infallible operation; this function only returns a Result because writing to the underlying stream might fail and it must provide a way to propagate the fact that an error has occurred back up the stack. Implementors § 1.0.0 · Source § impl Octal for i8 1.0.0 · Source § impl Octal for i16 1.0.0 · Source § impl Octal for i32 1.0.0 · Source § impl Octal for i64 1.0.0 · Source § impl Octal for i128 1.0.0 · Source § impl Octal for isize 1.0.0 · Source § impl Octal for u8 1.0.0 · Source § impl Octal for u16 1.0.0 · Source § impl Octal for u32 1.0.0 · Source § impl Octal for u64 1.0.0 · Source § impl Octal for u128 1.0.0 · Source § impl Octal for usize 1.0.0 · Source § impl<T> Octal for &T where T: Octal + ? Sized , 1.0.0 · Source § impl<T> Octal for &mut T where T: Octal + ? Sized , 1.28.0 · Source § impl<T> Octal for NonZero <T> where T: ZeroablePrimitive + Octal , 1.74.0 · Source § impl<T> Octal for Saturating <T> where T: Octal , 1.11.0 · Source § impl<T> Octal for Wrapping <T> where T: Octal , | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata | Documentation - 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 Documentation Crate level docs are thorough and include examples (C-CRATE-DOC) See RFC 1687 . All items have a rustdoc example (C-EXAMPLE) Every public module, trait, struct, enum, function, method, macro, and type definition should have an example that exercises the functionality. This guideline should be applied within reason. A link to an applicable example on another item may be sufficient. For example if exactly one function uses a particular type, it may be appropriate to write a single example on either the function or the type and link to it from the other. The purpose of an example is not always to show how to use the item. Readers can be expected to understand how to invoke functions, match on enums, and other fundamental tasks. Rather, an example is often intended to show why someone would want to use the item. // This would be a poor example of using clone(). It mechanically shows *how* to // call clone(), but does nothing to show *why* somebody would want this. fn main() { let hello = "hello"; hello.clone(); } Examples use ? , not try! , not unwrap (C-QUESTION-MARK) Like it or not, example code is often copied verbatim by users. Unwrapping an error should be a conscious decision that the user needs to make. A common way of structuring fallible example code is the following. The lines beginning with # are compiled by cargo test when building the example but will not appear in user-visible rustdoc. /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box<dyn Error>> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` Function docs include error, panic, and safety considerations (C-FAILURE) Error conditions should be documented in an "Errors" section. This applies to trait methods as well -- trait methods for which the implementation is allowed or expected to return an error should be documented with an "Errors" section. For example in the standard library, Some implementations of the std::io::Read::read trait method may return an error. /// Pull some bytes from this source into the specified buffer, returning /// how many bytes were read. /// /// ... lots more info ... /// /// # Errors /// /// If this function encounters any form of I/O or other error, an error /// variant will be returned. If an error is returned then it must be /// guaranteed that no bytes were read. Panic conditions should be documented in a "Panics" section. This applies to trait methods as well -- traits methods for which the implementation is allowed or expected to panic should be documented with a "Panics" section. In the standard library the Vec::insert method may panic. /// Inserts an element at position `index` within the vector, shifting all /// elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. It is not necessary to document all conceivable panic cases, especially if the panic occurs in logic provided by the caller. For example documenting the Display panic in the following code seems excessive. But when in doubt, err on the side of documenting more panic cases. #![allow(unused)] fn main() { /// # Panics /// /// This function panics if `T`'s implementation of `Display` panics. pub fn print<T: Display>(t: T) { println!("{}", t.to_string()); } } Unsafe functions should be documented with a "Safety" section that explains all invariants that the caller is responsible for upholding to use the function correctly. The unsafe std::ptr::read requires the following of the caller. /// Reads the value from `src` without moving it. This leaves the /// memory in `src` unchanged. /// /// # Safety /// /// Beyond accepting a raw pointer, this is unsafe because it semantically /// moves the value out of `src` without preventing further usage of `src`. /// If `T` is not `Copy`, then care must be taken to ensure that the value at /// `src` is not used before the data is overwritten again (e.g. with `write`, /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use /// because it will attempt to drop the value previously at `*src`. /// /// The pointer must be aligned; use `read_unaligned` if that is not the case. Prose contains hyperlinks to relevant things (C-LINK) Regular links can be added inline with the usual markdown syntax of [text](url) . Links to other types can be added by marking them with [`text`] , then adding the link target in a new line at the end of the docstring with [`text`]: <target> , where <target> is described below. Link targets to methods within the same type usually look like this: [`serialize_struct`]: #method.serialize_struct Link targets to other types usually look like this: [`Deserialize`]: trait.Deserialize.html Link targets may also point to a parent or child module: [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html This guideline is officially recommended by RFC 1574 under the heading "Link all the things" . Cargo.toml includes all common metadata (C-METADATA) The [package] section of Cargo.toml should include the following values: authors description license repository keywords categories In addition, there are two optional metadata fields: documentation homepage By default, crates.io links to documentation for the crate on docs.rs . The documentation metadata only needs to be set if the documentation is hosted somewhere other than docs.rs , for example because the crate links against a shared library that is not available in the build environment of docs.rs . The homepage metadata should only be set if there is a unique website for the crate other than the source repository or API documentation. Do not make homepage redundant with either the documentation or repository values. For example, serde sets homepage to https://serde.rs , a dedicated website. Release notes document all significant changes (C-RELNOTES) Users of the crate can read the release notes to find a summary of what changed in each published release of the crate. A link to the release notes, or the notes themselves, should be included in the crate-level documentation and/or the repository linked in Cargo.toml. Breaking changes (as defined in RFC 1105 ) should be clearly identified in the release notes. If using Git to track the source of a crate, every release published to crates.io should have a corresponding tag identifying the commit that was published. A similar process should be used for non-Git VCS tools as well. # Tag the current commit GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 git push --tags Annotated tags are preferred because some Git commands ignore unannotated tags if any annotated tags exist. Examples Serde 1.0.0 release notes Serde 0.9.8 release notes Serde 0.9.0 release notes Diesel change log Rustdoc does not show unhelpful implementation details (C-HIDDEN) Rustdoc is supposed to include everything users need to use the crate fully and nothing more. It is fine to explain relevant implementation details in prose but they should not be real entries in the documentation. Especially be selective about which impls are visible in rustdoc -- all the ones that users would need for using the crate fully, but no others. In the following code the rustdoc of PublicError by default would show the From<PrivateError> impl. We choose to hide it with #[doc(hidden)] because users can never have a PrivateError in their code so this impl would never be relevant to them. #![allow(unused)] fn main() { // This error type is returned to users. pub struct PublicError { /* ... */ } // This error type is returned by some private helper functions. struct PrivateError { /* ... */ } // Enable use of `?` operator. #[doc(hidden)] impl From<PrivateError> for PublicError { fn from(err: PrivateError) -> PublicError { /* ... */ } } } pub(crate) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/items/implementations.html | Implementations - 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 .impl] Implementations [items .impl .syntax] Syntax Implementation → InherentImpl | TraitImpl InherentImpl → impl GenericParams ? Type WhereClause ? { InnerAttribute * AssociatedItem * } TraitImpl → unsafe ? impl GenericParams ? ! ? TypePath for Type WhereClause ? { InnerAttribute * AssociatedItem * } Show Railroad Implementation InherentImpl TraitImpl InherentImpl impl GenericParams Type WhereClause { InnerAttribute AssociatedItem } TraitImpl unsafe impl GenericParams ! TypePath for Type WhereClause { InnerAttribute AssociatedItem } [items .impl .intro] An implementation is an item that associates items with an implementing type . Implementations are defined with the keyword impl and contain functions that belong to an instance of the type that is being implemented or to the type statically. [items .impl .kinds] There are two types of implementations: inherent implementations trait implementations [items .impl .inherent] Inherent implementations [items .impl .inherent .intro] An inherent implementation is defined as the sequence of the impl keyword, generic type declarations, a path to a nominal type, a where clause, and a bracketed set of associable items. [items .impl .inherent .implementing-type] The nominal type is called the implementing type and the associable items are the associated items to the implementing type. [items .impl .inherent .associated-items] Inherent implementations associate the contained items to the implementing type. [items .impl .inherent .associated-items .allowed-items] Inherent implementations can contain associated functions (including methods ) and associated constants . [items .impl .inherent .type-alias] They cannot contain associated type aliases. [items .impl .inherent .associated-item-path] The path to an associated item is any path to the implementing type, followed by the associated item’s identifier as the final path component. [items .impl .inherent .coherence] A type can also have multiple inherent implementations. An implementing type must be defined within the same crate as the original type definition. pub mod color { pub struct Color(pub u8, pub u8, pub u8); impl Color { pub const WHITE: Color = Color(255, 255, 255); } } mod values { use super::color::Color; impl Color { pub fn red() -> Color { Color(255, 0, 0) } } } pub use self::color::Color; fn main() { // Actual path to the implementing type and impl in the same module. color::Color::WHITE; // Impl blocks in different modules are still accessed through a path to the type. color::Color::red(); // Re-exported paths to the implementing type also work. Color::red(); // Does not work, because use in `values` is not pub. // values::Color::red(); } [items .impl .trait] Trait implementations [items .impl .trait .intro] A trait implementation is defined like an inherent implementation except that the optional generic type declarations are followed by a trait , followed by the keyword for , followed by a path to a nominal type. [items .impl .trait .implemented-trait] The trait is known as the implemented trait . The implementing type implements the implemented trait. [items .impl .trait .def-requirement] A trait implementation must define all non-default associated items declared by the implemented trait, may redefine default associated items defined by the implemented trait, and cannot define any other items. [items .impl .trait .associated-item-path] The path to the associated items is < followed by a path to the implementing type followed by as followed by a path to the trait followed by > as a path component followed by the associated item’s path component. [items .impl .trait .safety] Unsafe traits require the trait implementation to begin with the unsafe keyword. #![allow(unused)] fn main() { #[derive(Copy, Clone)] struct Point {x: f64, y: f64}; type Surface = i32; struct BoundingBox {x: f64, y: f64, width: f64, height: f64}; trait Shape { fn draw(&self, s: Surface); fn bounding_box(&self) -> BoundingBox; } fn do_draw_circle(s: Surface, c: Circle) { } struct Circle { radius: f64, center: Point, } impl Copy for Circle {} impl Clone for Circle { fn clone(&self) -> Circle { *self } } impl Shape for Circle { fn draw(&self, s: Surface) { do_draw_circle(s, *self); } fn bounding_box(&self) -> BoundingBox { let r = self.radius; BoundingBox { x: self.center.x - r, y: self.center.y - r, width: 2.0 * r, height: 2.0 * r, } } } } [items .impl .trait .coherence] Trait implementation coherence [items .impl .trait .coherence .intro] A trait implementation is considered incoherent if either the orphan rules check fails or there are overlapping implementation instances. [items .impl .trait .coherence .overlapping] Two trait implementations overlap when there is a non-empty intersection of the traits the implementation is for, the implementations can be instantiated with the same type. [items .impl .trait .orphan-rule] Orphan rules [items .impl .trait .orphan-rule .intro] The orphan rule states that a trait implementation is only allowed if either the trait or at least one of the types in the implementation is defined in the current crate. It prevents conflicting trait implementations across different crates and is key to ensuring coherence. An orphan implementation is one that implements a foreign trait for a foreign type. If these were freely allowed, two crates could implement the same trait for the same type in incompatible ways, creating a situation where adding or updating a dependency could break compilation due to conflicting implementations. The orphan rule enables library authors to add new implementations to their traits without fear that they’ll break downstream code. Without these restrictions, a library couldn’t add an implementation like impl<T: Display> MyTrait for T without potentially conflicting with downstream implementations. [items .impl .trait .orphan-rule .general] Given impl<P1..=Pn> Trait<T1..=Tn> for T0 , an impl is valid only if at least one of the following is true: Trait is a local trait All of At least one of the types T0..=Tn must be a local type . Let Ti be the first such type. No uncovered type parameters P1..=Pn may appear in T0..Ti (excluding Ti ) [items .impl .trait .uncovered-param] Only the appearance of uncovered type parameters is restricted. [items .impl .trait .fundamental] Note that for the purposes of coherence, fundamental types are special. The T in Box<T> is not considered covered, and Box<LocalType> is considered local. [items .impl .generics] Generic implementations [items .impl .generics .intro] An implementation can take generic parameters , which can be used in the rest of the implementation. Implementation parameters are written directly after the impl keyword. #![allow(unused)] fn main() { trait Seq<T> { fn dummy(&self, _: T) { } } impl<T> Seq<T> for Vec<T> { /* ... */ } impl Seq<bool> for u32 { /* Treat the integer as a sequence of bits */ } } [items .impl .generics .usage] Generic parameters constrain an implementation if the parameter appears at least once in one of: The implemented trait, if it has one The implementing type As an associated type in the bounds of a type that contains another parameter that constrains the implementation [items .impl .generics .constrain] Type and const parameters must always constrain the implementation. Lifetimes must constrain the implementation if the lifetime is used in an associated type. Examples of constraining situations: #![allow(unused)] fn main() { trait Trait{} trait GenericTrait<T> {} trait HasAssocType { type Ty; } struct Struct; struct GenericStruct<T>(T); struct ConstGenericStruct<const N: usize>([(); N]); // T constrains by being an argument to GenericTrait. impl<T> GenericTrait<T> for i32 { /* ... */ } // T constrains by being an argument to GenericStruct impl<T> Trait for GenericStruct<T> { /* ... */ } // Likewise, N constrains by being an argument to ConstGenericStruct impl<const N: usize> Trait for ConstGenericStruct<N> { /* ... */ } // T constrains by being in an associated type in a bound for type `U` which is // itself a generic parameter constraining the trait. impl<T, U> GenericTrait<U> for u32 where U: HasAssocType<Ty = T> { /* ... */ } // Like previous, except the type is `(U, isize)`. `U` appears inside the type // that includes `T`, and is not the type itself. impl<T, U> GenericStruct<U> where (U, isize): HasAssocType<Ty = T> { /* ... */ } } Examples of non-constraining situations: #![allow(unused)] fn main() { // The rest of these are errors, since they have type or const parameters that // do not constrain. // T does not constrain since it does not appear at all. impl<T> Struct { /* ... */ } // N does not constrain for the same reason. impl<const N: usize> Struct { /* ... */ } // Usage of T inside the implementation does not constrain the impl. impl<T> Struct { fn uses_t(t: &T) { /* ... */ } } // T is used as an associated type in the bounds for U, but U does not constrain. impl<T, U> Struct where U: HasAssocType<Ty = T> { /* ... */ } // T is used in the bounds, but not as an associated type, so it does not constrain. impl<T, U> GenericTrait<U> for u32 where U: GenericTrait<T> {} } Example of an allowed unconstraining lifetime parameter: #![allow(unused)] fn main() { struct Struct; impl<'a> Struct {} } Example of a disallowed unconstraining lifetime parameter: #![allow(unused)] fn main() { struct Struct; trait HasAssocType { type Ty; } impl<'a> HasAssocType for Struct { type Ty = &'a Struct; } } [items .impl .attributes] Attributes on implementations Implementations may contain outer attributes before the impl keyword and inner attributes inside the brackets that contain the associated items. Inner attributes must come before any associated items. The attributes that have meaning here are cfg , deprecated , doc , and the lint check attributes . | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/documentation.html#rustdoc-does-not-show-unhelpful-implementation-details-c-hidden | Documentation - 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 Documentation Crate level docs are thorough and include examples (C-CRATE-DOC) See RFC 1687 . All items have a rustdoc example (C-EXAMPLE) Every public module, trait, struct, enum, function, method, macro, and type definition should have an example that exercises the functionality. This guideline should be applied within reason. A link to an applicable example on another item may be sufficient. For example if exactly one function uses a particular type, it may be appropriate to write a single example on either the function or the type and link to it from the other. The purpose of an example is not always to show how to use the item. Readers can be expected to understand how to invoke functions, match on enums, and other fundamental tasks. Rather, an example is often intended to show why someone would want to use the item. // This would be a poor example of using clone(). It mechanically shows *how* to // call clone(), but does nothing to show *why* somebody would want this. fn main() { let hello = "hello"; hello.clone(); } Examples use ? , not try! , not unwrap (C-QUESTION-MARK) Like it or not, example code is often copied verbatim by users. Unwrapping an error should be a conscious decision that the user needs to make. A common way of structuring fallible example code is the following. The lines beginning with # are compiled by cargo test when building the example but will not appear in user-visible rustdoc. /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box<dyn Error>> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` Function docs include error, panic, and safety considerations (C-FAILURE) Error conditions should be documented in an "Errors" section. This applies to trait methods as well -- trait methods for which the implementation is allowed or expected to return an error should be documented with an "Errors" section. For example in the standard library, Some implementations of the std::io::Read::read trait method may return an error. /// Pull some bytes from this source into the specified buffer, returning /// how many bytes were read. /// /// ... lots more info ... /// /// # Errors /// /// If this function encounters any form of I/O or other error, an error /// variant will be returned. If an error is returned then it must be /// guaranteed that no bytes were read. Panic conditions should be documented in a "Panics" section. This applies to trait methods as well -- traits methods for which the implementation is allowed or expected to panic should be documented with a "Panics" section. In the standard library the Vec::insert method may panic. /// Inserts an element at position `index` within the vector, shifting all /// elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. It is not necessary to document all conceivable panic cases, especially if the panic occurs in logic provided by the caller. For example documenting the Display panic in the following code seems excessive. But when in doubt, err on the side of documenting more panic cases. #![allow(unused)] fn main() { /// # Panics /// /// This function panics if `T`'s implementation of `Display` panics. pub fn print<T: Display>(t: T) { println!("{}", t.to_string()); } } Unsafe functions should be documented with a "Safety" section that explains all invariants that the caller is responsible for upholding to use the function correctly. The unsafe std::ptr::read requires the following of the caller. /// Reads the value from `src` without moving it. This leaves the /// memory in `src` unchanged. /// /// # Safety /// /// Beyond accepting a raw pointer, this is unsafe because it semantically /// moves the value out of `src` without preventing further usage of `src`. /// If `T` is not `Copy`, then care must be taken to ensure that the value at /// `src` is not used before the data is overwritten again (e.g. with `write`, /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use /// because it will attempt to drop the value previously at `*src`. /// /// The pointer must be aligned; use `read_unaligned` if that is not the case. Prose contains hyperlinks to relevant things (C-LINK) Regular links can be added inline with the usual markdown syntax of [text](url) . Links to other types can be added by marking them with [`text`] , then adding the link target in a new line at the end of the docstring with [`text`]: <target> , where <target> is described below. Link targets to methods within the same type usually look like this: [`serialize_struct`]: #method.serialize_struct Link targets to other types usually look like this: [`Deserialize`]: trait.Deserialize.html Link targets may also point to a parent or child module: [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html This guideline is officially recommended by RFC 1574 under the heading "Link all the things" . Cargo.toml includes all common metadata (C-METADATA) The [package] section of Cargo.toml should include the following values: authors description license repository keywords categories In addition, there are two optional metadata fields: documentation homepage By default, crates.io links to documentation for the crate on docs.rs . The documentation metadata only needs to be set if the documentation is hosted somewhere other than docs.rs , for example because the crate links against a shared library that is not available in the build environment of docs.rs . The homepage metadata should only be set if there is a unique website for the crate other than the source repository or API documentation. Do not make homepage redundant with either the documentation or repository values. For example, serde sets homepage to https://serde.rs , a dedicated website. Release notes document all significant changes (C-RELNOTES) Users of the crate can read the release notes to find a summary of what changed in each published release of the crate. A link to the release notes, or the notes themselves, should be included in the crate-level documentation and/or the repository linked in Cargo.toml. Breaking changes (as defined in RFC 1105 ) should be clearly identified in the release notes. If using Git to track the source of a crate, every release published to crates.io should have a corresponding tag identifying the commit that was published. A similar process should be used for non-Git VCS tools as well. # Tag the current commit GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 git push --tags Annotated tags are preferred because some Git commands ignore unannotated tags if any annotated tags exist. Examples Serde 1.0.0 release notes Serde 0.9.8 release notes Serde 0.9.0 release notes Diesel change log Rustdoc does not show unhelpful implementation details (C-HIDDEN) Rustdoc is supposed to include everything users need to use the crate fully and nothing more. It is fine to explain relevant implementation details in prose but they should not be real entries in the documentation. Especially be selective about which impls are visible in rustdoc -- all the ones that users would need for using the crate fully, but no others. In the following code the rustdoc of PublicError by default would show the From<PrivateError> impl. We choose to hide it with #[doc(hidden)] because users can never have a PrivateError in their code so this impl would never be relevant to them. #![allow(unused)] fn main() { // This error type is returned to users. pub struct PublicError { /* ... */ } // This error type is returned by some private helper functions. struct PrivateError { /* ... */ } // Enable use of `?` operator. #[doc(hidden)] impl From<PrivateError> for PublicError { fn from(err: PrivateError) -> PublicError { /* ... */ } } } pub(crate) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/items/modules.html | Modules - 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 .mod] Modules [items .mod .syntax] Syntax Module → unsafe ? mod IDENTIFIER ; | unsafe ? mod IDENTIFIER { InnerAttribute * Item * } Show Railroad Module unsafe mod IDENTIFIER ; unsafe mod IDENTIFIER { InnerAttribute Item } [items .mod .intro] A module is a container for zero or more items . [items .mod .def] A module item is a module, surrounded in braces, named, and prefixed with the keyword mod . A module item introduces a new, named module into the tree of modules making up a crate. [items .mod .nesting] Modules can nest arbitrarily. An example of a module: #![allow(unused)] fn main() { mod math { type Complex = (f64, f64); fn sin(f: f64) -> f64 { /* ... */ unimplemented!(); } fn cos(f: f64) -> f64 { /* ... */ unimplemented!(); } fn tan(f: f64) -> f64 { /* ... */ unimplemented!(); } } } [items .mod .namespace] Modules are defined in the type namespace of the module or block where they are located. [items .mod .multiple-items] It is an error to define multiple items with the same name in the same namespace within a module. See the scopes chapter for more details on restrictions and shadowing behavior. [items .mod .unsafe] The unsafe keyword is syntactically allowed to appear before the mod keyword, but it is rejected at a semantic level. This allows macros to consume the syntax and make use of the unsafe keyword, before removing it from the token stream. [items .mod .outlined] Module source filenames [items .mod .outlined .intro] A module without a body is loaded from an external file. When the module does not have a path attribute, the path to the file mirrors the logical module path . [items .mod .outlined .search] Ancestor module path components are directories, and the module’s contents are in a file with the name of the module plus the .rs extension. For example, the following module structure can have this corresponding filesystem structure: Module Path Filesystem Path File Contents crate lib.rs mod util; crate::util util.rs mod config; crate::util::config util/config.rs [items .mod .outlined .search-mod] Module filenames may also be the name of the module as a directory with the contents in a file named mod.rs within that directory. The above example can alternately be expressed with crate::util ’s contents in a file named util/mod.rs . It is not allowed to have both util.rs and util/mod.rs . Note Prior to rustc 1.30, using mod.rs files was the way to load a module with nested children. It is encouraged to use the new naming convention as it is more consistent, and avoids having many files named mod.rs within a project. [items .mod .outlined .path] The path attribute [items .mod .outlined .path .intro] The directories and files used for loading external file modules can be influenced with the path attribute. [items .mod .outlined .path .search] For path attributes on modules not inside inline module blocks, the file path is relative to the directory the source file is located. For example, the following code snippet would use the paths shown based on where it is located: #[path = "foo.rs"] mod c; Source File c ’s File Location c ’s Module Path src/a/b.rs src/a/foo.rs crate::a::b::c src/a/mod.rs src/a/foo.rs crate::a::c [items .mod .outlined .path .search-nested] For path attributes inside inline module blocks, the relative location of the file path depends on the kind of source file the path attribute is located in. “mod-rs” source files are root modules (such as lib.rs or main.rs ) and modules with files named mod.rs . “non-mod-rs” source files are all other module files. Paths for path attributes inside inline module blocks in a mod-rs file are relative to the directory of the mod-rs file including the inline module components as directories. For non-mod-rs files, it is the same except the path starts with a directory with the name of the non-mod-rs module. For example, the following code snippet would use the paths shown based on where it is located: mod inline { #[path = "other.rs"] mod inner; } Source File inner ’s File Location inner ’s Module Path src/a/b.rs src/a/b/inline/other.rs crate::a::b::inline::inner src/a/mod.rs src/a/inline/other.rs crate::a::inline::inner An example of combining the above rules of path attributes on inline modules and nested modules within (applies to both mod-rs and non-mod-rs files): #[path = "thread_files"] mod thread { // Load the `local_data` module from `thread_files/tls.rs` relative to // this source file's directory. #[path = "tls.rs"] mod local_data; } [items .mod .attributes] Attributes on modules [items .mod .attributes .intro] Modules, like all items, accept outer attributes. They also accept inner attributes: either after { for a module with a body, or at the beginning of the source file, after the optional BOM and shebang. [items .mod .attributes .supported] The built-in attributes that have meaning on a module are cfg , deprecated , doc , the lint check attributes , path , and no_implicit_prelude . Modules also accept macro attributes. | 2026-01-13T09:29:13 |
https://rust-lang.github.io/api-guidelines/documentation.html#crate-level-docs-are-thorough-and-include-examples-c-crate-doc | Documentation - 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 Documentation Crate level docs are thorough and include examples (C-CRATE-DOC) See RFC 1687 . All items have a rustdoc example (C-EXAMPLE) Every public module, trait, struct, enum, function, method, macro, and type definition should have an example that exercises the functionality. This guideline should be applied within reason. A link to an applicable example on another item may be sufficient. For example if exactly one function uses a particular type, it may be appropriate to write a single example on either the function or the type and link to it from the other. The purpose of an example is not always to show how to use the item. Readers can be expected to understand how to invoke functions, match on enums, and other fundamental tasks. Rather, an example is often intended to show why someone would want to use the item. // This would be a poor example of using clone(). It mechanically shows *how* to // call clone(), but does nothing to show *why* somebody would want this. fn main() { let hello = "hello"; hello.clone(); } Examples use ? , not try! , not unwrap (C-QUESTION-MARK) Like it or not, example code is often copied verbatim by users. Unwrapping an error should be a conscious decision that the user needs to make. A common way of structuring fallible example code is the following. The lines beginning with # are compiled by cargo test when building the example but will not appear in user-visible rustdoc. /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box<dyn Error>> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` Function docs include error, panic, and safety considerations (C-FAILURE) Error conditions should be documented in an "Errors" section. This applies to trait methods as well -- trait methods for which the implementation is allowed or expected to return an error should be documented with an "Errors" section. For example in the standard library, Some implementations of the std::io::Read::read trait method may return an error. /// Pull some bytes from this source into the specified buffer, returning /// how many bytes were read. /// /// ... lots more info ... /// /// # Errors /// /// If this function encounters any form of I/O or other error, an error /// variant will be returned. If an error is returned then it must be /// guaranteed that no bytes were read. Panic conditions should be documented in a "Panics" section. This applies to trait methods as well -- traits methods for which the implementation is allowed or expected to panic should be documented with a "Panics" section. In the standard library the Vec::insert method may panic. /// Inserts an element at position `index` within the vector, shifting all /// elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. It is not necessary to document all conceivable panic cases, especially if the panic occurs in logic provided by the caller. For example documenting the Display panic in the following code seems excessive. But when in doubt, err on the side of documenting more panic cases. #![allow(unused)] fn main() { /// # Panics /// /// This function panics if `T`'s implementation of `Display` panics. pub fn print<T: Display>(t: T) { println!("{}", t.to_string()); } } Unsafe functions should be documented with a "Safety" section that explains all invariants that the caller is responsible for upholding to use the function correctly. The unsafe std::ptr::read requires the following of the caller. /// Reads the value from `src` without moving it. This leaves the /// memory in `src` unchanged. /// /// # Safety /// /// Beyond accepting a raw pointer, this is unsafe because it semantically /// moves the value out of `src` without preventing further usage of `src`. /// If `T` is not `Copy`, then care must be taken to ensure that the value at /// `src` is not used before the data is overwritten again (e.g. with `write`, /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use /// because it will attempt to drop the value previously at `*src`. /// /// The pointer must be aligned; use `read_unaligned` if that is not the case. Prose contains hyperlinks to relevant things (C-LINK) Regular links can be added inline with the usual markdown syntax of [text](url) . Links to other types can be added by marking them with [`text`] , then adding the link target in a new line at the end of the docstring with [`text`]: <target> , where <target> is described below. Link targets to methods within the same type usually look like this: [`serialize_struct`]: #method.serialize_struct Link targets to other types usually look like this: [`Deserialize`]: trait.Deserialize.html Link targets may also point to a parent or child module: [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html This guideline is officially recommended by RFC 1574 under the heading "Link all the things" . Cargo.toml includes all common metadata (C-METADATA) The [package] section of Cargo.toml should include the following values: authors description license repository keywords categories In addition, there are two optional metadata fields: documentation homepage By default, crates.io links to documentation for the crate on docs.rs . The documentation metadata only needs to be set if the documentation is hosted somewhere other than docs.rs , for example because the crate links against a shared library that is not available in the build environment of docs.rs . The homepage metadata should only be set if there is a unique website for the crate other than the source repository or API documentation. Do not make homepage redundant with either the documentation or repository values. For example, serde sets homepage to https://serde.rs , a dedicated website. Release notes document all significant changes (C-RELNOTES) Users of the crate can read the release notes to find a summary of what changed in each published release of the crate. A link to the release notes, or the notes themselves, should be included in the crate-level documentation and/or the repository linked in Cargo.toml. Breaking changes (as defined in RFC 1105 ) should be clearly identified in the release notes. If using Git to track the source of a crate, every release published to crates.io should have a corresponding tag identifying the commit that was published. A similar process should be used for non-Git VCS tools as well. # Tag the current commit GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 git push --tags Annotated tags are preferred because some Git commands ignore unannotated tags if any annotated tags exist. Examples Serde 1.0.0 release notes Serde 0.9.8 release notes Serde 0.9.0 release notes Diesel change log Rustdoc does not show unhelpful implementation details (C-HIDDEN) Rustdoc is supposed to include everything users need to use the crate fully and nothing more. It is fine to explain relevant implementation details in prose but they should not be real entries in the documentation. Especially be selective about which impls are visible in rustdoc -- all the ones that users would need for using the crate fully, but no others. In the following code the rustdoc of PublicError by default would show the From<PrivateError> impl. We choose to hide it with #[doc(hidden)] because users can never have a PrivateError in their code so this impl would never be relevant to them. #![allow(unused)] fn main() { // This error type is returned to users. pub struct PublicError { /* ... */ } // This error type is returned by some private helper functions. struct PrivateError { /* ... */ } // Enable use of `?` operator. #[doc(hidden)] impl From<PrivateError> for PublicError { fn from(err: PrivateError) -> PublicError { /* ... */ } } } pub(crate) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/reference/paths.html#railroad-SimplePath | Paths - 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 [paths] Paths [paths .intro] A path is a sequence of one or more path segments separated by :: tokens. Paths are used to refer to items , values, types , macros , and attributes . Two examples of simple paths consisting of only identifier segments: x; x::y::z; Types of paths [paths .simple] Simple paths [paths .simple .syntax] Syntax SimplePath → :: ? SimplePathSegment ( :: SimplePathSegment ) * SimplePathSegment → IDENTIFIER | super | self | crate | $crate Show Railroad SimplePath :: SimplePathSegment :: SimplePathSegment SimplePathSegment IDENTIFIER super self crate $crate [paths .simple .intro] Simple paths are used in visibility markers, attributes , macros , and use items. For example: #![allow(unused)] fn main() { use std::io::{self, Write}; mod m { #[clippy::cyclomatic_complexity = "0"] pub (in super) fn f1() {} } } [paths .expr] Paths in expressions [paths .expr .syntax] Syntax PathInExpression → :: ? PathExprSegment ( :: PathExprSegment ) * PathExprSegment → PathIdentSegment ( :: GenericArgs ) ? PathIdentSegment → IDENTIFIER | super | self | Self | crate | $crate GenericArgs → < > | < ( GenericArg , ) * GenericArg , ? > GenericArg → Lifetime | Type | GenericArgsConst | GenericArgsBinding | GenericArgsBounds GenericArgsConst → BlockExpression | LiteralExpression | - LiteralExpression | SimplePathSegment GenericArgsBinding → IDENTIFIER GenericArgs ? = Type GenericArgsBounds → IDENTIFIER GenericArgs ? : TypeParamBounds Show Railroad PathInExpression :: PathExprSegment :: PathExprSegment PathExprSegment PathIdentSegment :: GenericArgs PathIdentSegment IDENTIFIER super self Self crate $crate GenericArgs < > < GenericArg , GenericArg , > GenericArg Lifetime Type GenericArgsConst GenericArgsBinding GenericArgsBounds GenericArgsConst BlockExpression LiteralExpression - LiteralExpression SimplePathSegment GenericArgsBinding IDENTIFIER GenericArgs = Type GenericArgsBounds IDENTIFIER GenericArgs : TypeParamBounds [paths .expr .intro] Paths in expressions allow for paths with generic arguments to be specified. They are used in various places in expressions and patterns . [paths .expr .turbofish] The :: token is required before the opening < for generic arguments to avoid ambiguity with the less-than operator. This is colloquially known as “turbofish” syntax. #![allow(unused)] fn main() { (0..10).collect::<Vec<_>>(); Vec::<u8>::with_capacity(1024); } [paths .expr .argument-order] The order of generic arguments is restricted to lifetime arguments, then type arguments, then const arguments, then equality constraints. [paths .expr .complex-const-params] Const arguments must be surrounded by braces unless they are a literal , an inferred const , or a single segment path. An inferred const may not be surrounded by braces. #![allow(unused)] fn main() { mod m { pub const C: usize = 1; } const C: usize = m::C; fn f<const N: usize>() -> [u8; N] { [0; N] } let _ = f::<1>(); // Literal. let _: [_; 1] = f::<_>(); // Inferred const. let _: [_; 1] = f::<(((_)))>(); // Inferred const. let _ = f::<C>(); // Single segment path. let _ = f::<{ m::C }>(); // Multi-segment path must be braced. } #![allow(unused)] fn main() { fn f<const N: usize>() -> [u8; N] { [0; _] } let _: [_; 1] = f::<{ _ }>(); // ^ ERROR `_` not allowed here } 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 . [paths .expr .impl-trait-params] The synthetic type parameters corresponding to impl Trait types are implicit, and these cannot be explicitly specified. [paths .qualified] Qualified paths [paths .qualified .syntax] Syntax QualifiedPathInExpression → QualifiedPathType ( :: PathExprSegment ) + QualifiedPathType → < Type ( as TypePath ) ? > QualifiedPathInType → QualifiedPathType ( :: TypePathSegment ) + Show Railroad QualifiedPathInExpression QualifiedPathType :: PathExprSegment QualifiedPathType < Type as TypePath > QualifiedPathInType QualifiedPathType :: TypePathSegment [paths .qualified .intro] Fully qualified paths allow for disambiguating the path for trait implementations and for specifying canonical paths . When used in a type specification, it supports using the type syntax specified below. #![allow(unused)] fn main() { struct S; impl S { fn f() { println!("S"); } } trait T1 { fn f() { println!("T1 f"); } } impl T1 for S {} trait T2 { fn f() { println!("T2 f"); } } impl T2 for S {} S::f(); // Calls the inherent impl. <S as T1>::f(); // Calls the T1 trait function. <S as T2>::f(); // Calls the T2 trait function. } [paths .type] Paths in types [paths .type .syntax] Syntax TypePath → :: ? TypePathSegment ( :: TypePathSegment ) * TypePathSegment → PathIdentSegment ( :: ? ( GenericArgs | TypePathFn ) ) ? TypePathFn → ( TypePathFnInputs ? ) ( -> TypeNoBounds ) ? TypePathFnInputs → Type ( , Type ) * , ? Show Railroad TypePath :: TypePathSegment :: TypePathSegment TypePathSegment PathIdentSegment :: GenericArgs TypePathFn TypePathFn ( TypePathFnInputs ) -> TypeNoBounds TypePathFnInputs Type , Type , [paths .type .intro] Type paths are used within type definitions, trait bounds, type parameter bounds, and qualified paths. [paths .type .turbofish] Although the :: token is allowed before the generics arguments, it is not required because there is no ambiguity like there is in PathInExpression . #![allow(unused)] fn main() { mod ops { pub struct Range<T> {f1: T} pub trait Index<T> {} pub struct Example<'a> {f1: &'a i32} } struct S; impl ops::Index<ops::Range<usize>> for S { /*...*/ } fn i<'a>() -> impl Iterator<Item = ops::Example<'a>> { // ... const EXAMPLE: Vec<ops::Example<'static>> = Vec::new(); EXAMPLE.into_iter() } type G = std::boxed::Box<dyn std::ops::FnOnce(isize) -> isize>; } [paths .qualifiers] Path qualifiers Paths can be denoted with various leading qualifiers to change the meaning of how it is resolved. [paths .qualifiers .global-root] :: [paths .qualifiers .global-root .intro] Paths starting with :: are considered to be global paths where the segments of the path start being resolved from a place which differs based on edition. Each identifier in the path must resolve to an item. [paths .qualifiers .global-root .edition2018] 2018 Edition differences In the 2015 Edition, identifiers resolve from the “crate root” ( crate:: in the 2018 edition), which contains a variety of different items, including external crates, default crates such as std or core , and items in the top level of the crate (including use imports). Beginning with the 2018 Edition, paths starting with :: resolve from crates in the extern prelude . That is, they must be followed by the name of a crate. #![allow(unused)] fn main() { pub fn foo() { // In the 2018 edition, this accesses `std` via the extern prelude. // In the 2015 edition, this accesses `std` via the crate root. let now = ::std::time::Instant::now(); println!("{:?}", now); } } // 2015 Edition mod a { pub fn foo() {} } mod b { pub fn foo() { ::a::foo(); // call `a`'s foo function // In Rust 2018, `::a` would be interpreted as the crate `a`. } } fn main() {} [paths .qualifiers .mod-self] self [paths .qualifiers .mod-self .intro] self resolves the path relative to the current module. [paths .qualifiers .mod-self .restriction] self can only be used as the first segment, without a preceding :: . [paths .qualifiers .self-pat] In a method body, a path which consists of a single self segment resolves to the method’s self parameter. fn foo() {} fn bar() { self::foo(); } struct S(bool); impl S { fn baz(self) { self.0; } } fn main() {} [paths .qualifiers .type-self] Self [paths .qualifiers .type-self .intro] Self , with a capital “S”, is used to refer to the current type being implemented or defined. It may be used in the following situations: [paths .qualifiers .type-self .trait] In a trait definition, it refers to the type implementing the trait. [paths .qualifiers .type-self .impl] In an implementation , it refers to the type being implemented. When implementing a tuple or unit struct , it also refers to the constructor in the value namespace . [paths .qualifiers .type-self .type] In the definition of a struct , enumeration , or union , it refers to the type being defined. The definition is not allowed to be infinitely recursive (there must be an indirection). [paths .qualifiers .type-self .scope] The scope of Self behaves similarly to a generic parameter; see the Self scope section for more details. [paths .qualifiers .type-self .allowed-positions] Self can only be used as the first segment, without a preceding :: . [paths .qualifiers .type-self .no-generics] The Self path cannot include generic arguments (as in Self::<i32> ). #![allow(unused)] fn main() { trait T { type Item; const C: i32; // `Self` will be whatever type that implements `T`. fn new() -> Self; // `Self::Item` will be the type alias in the implementation. fn f(&self) -> Self::Item; } struct S; impl T for S { type Item = i32; const C: i32 = 9; fn new() -> Self { // `Self` is the type `S`. S } fn f(&self) -> Self::Item { // `Self::Item` is the type `i32`. Self::C // `Self::C` is the constant value `9`. } } // `Self` is in scope within the generics of a trait definition, // to refer to the type being defined. trait Add<Rhs = Self> { type Output; // `Self` can also reference associated items of the // type being implemented. fn add(self, rhs: Rhs) -> Self::Output; } struct NonEmptyList<T> { head: T, // A struct can reference itself (as long as it is not // infinitely recursive). tail: Option<Box<Self>>, } } [paths .qualifiers .super] super [paths .qualifiers .super .intro] super in a path resolves to the parent module. [paths .qualifiers .super .allowed-positions] It may only be used in leading segments of the path, possibly after an initial self segment. mod a { pub fn foo() {} } mod b { pub fn foo() { super::a::foo(); // call a's foo function } } fn main() {} [paths .qualifiers .super .repetition] super may be repeated several times after the first super or self to refer to ancestor modules. mod a { fn foo() {} mod b { mod c { fn foo() { super::super::foo(); // call a's foo function self::super::super::foo(); // call a's foo function } } } } fn main() {} [paths .qualifiers .crate] crate [paths .qualifiers .crate .intro] crate resolves the path relative to the current crate. [paths .qualifiers .crate .allowed-positions] crate can only be used as the first segment, without a preceding :: . fn foo() {} mod a { fn bar() { crate::foo(); } } fn main() {} [paths .qualifiers .macro-crate] $crate [paths .qualifiers .macro-crate .allowed-positions] $crate is only used within macro transcribers , and can only be used as the first segment, without a preceding :: . [paths .qualifiers .macro-crate .hygiene] $crate will expand to a path to access items from the top level of the crate where the macro is defined, regardless of which crate the macro is invoked. pub fn increment(x: u32) -> u32 { x + 1 } #[macro_export] macro_rules! inc { ($x:expr) => ( $crate::increment($x) ) } fn main() { } [paths .canonical] Canonical paths [paths .canonical .intro] Items defined in a module or implementation have a canonical path that corresponds to where within its crate it is defined. [paths .canonical .alias] All other paths to these items are aliases. [paths .canonical .def] The canonical path is defined as a path prefix appended by the path segment the item itself defines. [paths .canonical .non-canonical] Implementations and use declarations do not have canonical paths, although the items that implementations define do have them. Items defined in block expressions do not have canonical paths. Items defined in a module that does not have a canonical path do not have a canonical path. Associated items defined in an implementation that refers to an item without a canonical path, e.g. as the implementing type, the trait being implemented, a type parameter or bound on a type parameter, do not have canonical paths. [paths .canonical .module-prefix] The path prefix for modules is the canonical path to that module. [paths .canonical .bare-impl-prefix] For bare implementations, it is the canonical path of the item being implemented surrounded by angle ( <> ) brackets. [paths .canonical .trait-impl-prefix] For trait implementations , it is the canonical path of the item being implemented followed by as followed by the canonical path to the trait all surrounded in angle ( <> ) brackets. [paths .canonical .local-canonical-path] The canonical path is only meaningful within a given crate. There is no global namespace across crates; an item’s canonical path merely identifies it within the crate. // Comments show the canonical path of the item. mod a { // crate::a pub struct Struct; // crate::a::Struct pub trait Trait { // crate::a::Trait fn f(&self); // crate::a::Trait::f } impl Trait for Struct { fn f(&self) {} // <crate::a::Struct as crate::a::Trait>::f } impl Struct { fn g(&self) {} // <crate::a::Struct>::g } } mod without { // crate::without fn canonicals() { // crate::without::canonicals struct OtherStruct; // None trait OtherTrait { // None fn g(&self); // None } impl OtherTrait for OtherStruct { fn g(&self) {} // None } impl OtherTrait for crate::a::Struct { fn g(&self) {} // None } impl crate::a::Trait for OtherStruct { fn f(&self) {} // None } } } fn main() {} | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/std/fmt/trait.LowerHex.html | LowerHex in std::fmt - Rust This old browser is unsupported and will most likely display funky things. LowerHex std 1.92.0 (ded5c06cf 2025-12-08) Lower Hex Sections Examples Required Methods fmt Implementors In std:: fmt std :: fmt Trait Lower Hex Copy item path 1.0.0 · Source pub trait LowerHex { // Required method fn fmt (&self, f: &mut Formatter <'_>) -> Result < () , Error >; } Expand description x formatting. The LowerHex trait should format its output as a number in hexadecimal, with a through f in lower case. For primitive signed integers ( i8 to i128 , and isize ), negative values are formatted as the two’s complement representation. The alternate flag, # , adds a 0x in front of the output. For more information on formatters, see the module-level documentation . § Examples Basic usage with i32 : let y = 42 ; // 42 is '2a' in hex assert_eq! ( format! ( "{y:x}" ), "2a" ); assert_eq! ( format! ( "{y:#x}" ), "0x2a" ); assert_eq! ( format! ( "{:x}" , - 16 ), "fffffff0" ); Implementing LowerHex on a type: use std::fmt; struct Length(i32); impl fmt::LowerHex for Length { fn fmt( & self , f: &mut fmt::Formatter< '_ >) -> fmt::Result { let val = self . 0 ; fmt::LowerHex::fmt( & val, f) // delegate to i32's implementation } } let l = Length( 9 ); assert_eq! ( format! ( "l as hex is: {l:x}" ), "l as hex is: 9" ); assert_eq! ( format! ( "l as hex is: {l:#010x}" ), "l as hex is: 0x00000009" ); Required Methods § 1.0.0 · Source fn fmt (&self, f: &mut Formatter <'_>) -> Result < () , Error > Formats the value using the given formatter. § Errors This function should return Err if, and only if, the provided Formatter returns Err . String formatting is considered an infallible operation; this function only returns a Result because writing to the underlying stream might fail and it must provide a way to propagate the fact that an error has occurred back up the stack. Implementors § 1.0.0 · Source § impl LowerHex for i8 1.0.0 · Source § impl LowerHex for i16 1.0.0 · Source § impl LowerHex for i32 1.0.0 · Source § impl LowerHex for i64 1.0.0 · Source § impl LowerHex for i128 1.0.0 · Source § impl LowerHex for isize 1.0.0 · Source § impl LowerHex for u8 1.0.0 · Source § impl LowerHex for u16 1.0.0 · Source § impl LowerHex for u32 1.0.0 · Source § impl LowerHex for u64 1.0.0 · Source § impl LowerHex for u128 1.0.0 · Source § impl LowerHex for usize 1.0.0 · Source § impl<T> LowerHex for &T where T: LowerHex + ? Sized , 1.0.0 · Source § impl<T> LowerHex for &mut T where T: LowerHex + ? Sized , 1.28.0 · Source § impl<T> LowerHex for NonZero <T> where T: ZeroablePrimitive + LowerHex , 1.74.0 · Source § impl<T> LowerHex for Saturating <T> where T: LowerHex , 1.11.0 · Source § impl<T> LowerHex for Wrapping <T> where T: LowerHex , | 2026-01-13T09:29:13 |
https://www.mkdocs.org/dev-guide/plugins/ | Plugins - 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 MkDocs Plugins Installing Plugins Using Plugins Developing Plugins MkDocs Plugins A Guide to installing, using and creating MkDocs Plugins Installing Plugins Before a plugin can be used, it must be installed on the system. If you are using a plugin which comes with MkDocs, then it was installed when you installed MkDocs. However, to install third party plugins, you need to determine the appropriate package name and install it using pip : pip install mkdocs-foo-plugin Warning Installing an MkDocs plugin means installing a Python package and executing any code that the author has put in there. So, exercise the usual caution; there's no attempt at sandboxing. Once a plugin has been successfully installed, it is ready to use. It just needs to be enabled in the configuration file. The Catalog repository has a large ranked list of plugins that you can install and use. Using Plugins The plugins configuration option should contain a list of plugins to use when building the site. Each "plugin" must be a string name assigned to the plugin (see the documentation for a given plugin to determine its "name"). A plugin listed here must already be installed . plugins: - search Some plugins may provide configuration options of their own. If you would like to set any configuration options, then you can nest a key/value mapping ( option_name: option value ) of any options that a given plugin supports. Note that a colon ( : ) must follow the plugin name and then on a new line the option name and value must be indented and separated by a colon. If you would like to define multiple options for a single plugin, each option must be defined on a separate line. plugins: - search: lang: en foo: bar For information regarding the configuration options available for a given plugin, see that plugin's documentation. For a list of default plugins and how to override them, see the configuration documentation. Developing Plugins Like MkDocs, plugins must be written in Python. It is generally expected that each plugin would be distributed as a separate Python module, although it is possible to define multiple plugins in the same module. At a minimum, a MkDocs Plugin must consist of a BasePlugin subclass and an entry point which points to it. BasePlugin A subclass of mkdocs.plugins.BasePlugin should define the behavior of the plugin. The class generally consists of actions to perform on specific events in the build process as well as a configuration scheme for the plugin. All BasePlugin subclasses contain the following attributes: config_scheme A tuple of configuration validation instances. Each item must consist of a two item tuple in which the first item is the string name of the configuration option and the second item is an instance of mkdocs.config.config_options.BaseConfigOption or any of its subclasses. For example, the following config_scheme defines three configuration options: foo , which accepts a string; bar , which accepts an integer; and baz , which accepts a boolean value. class MyPlugin(mkdocs.plugins.BasePlugin): config_scheme = ( ('foo', mkdocs.config.config_options.Type(str, default='a default value')), ('bar', mkdocs.config.config_options.Type(int, default=0)), ('baz', mkdocs.config.config_options.Type(bool, default=True)) ) New in version 1.4 Subclassing Config to specify the config schema To get type safety benefits, if you're targeting only MkDocs 1.4+, define the config schema as a class instead: class MyPluginConfig(mkdocs.config.base.Config): foo = mkdocs.config.config_options.Type(str, default='a default value') bar = mkdocs.config.config_options.Type(int, default=0) baz = mkdocs.config.config_options.Type(bool, default=True) class MyPlugin(mkdocs.plugins.BasePlugin[MyPluginConfig]): ... Examples of config definitions Example from mkdocs.config import base, config_options as c class _ValidationOptions(base.Config): enabled = c.Type(bool, default=True) verbose = c.Type(bool, default=False) skip_checks = c.ListOfItems(c.Choice(('foo', 'bar', 'baz')), default=[]) class MyPluginConfig(base.Config): definition_file = c.File(exists=True) # required checksum_file = c.Optional(c.File(exists=True)) # can be None but must exist if specified validation = c.SubConfig(_ValidationOptions) From the user's point of view SubConfig is similar to Type(dict) , it's just that it also retains full ability for validation: you define all valid keys and what each value should adhere to. And ListOfItems is similar to Type(list) , but again, we define the constraint that each value must adhere to. This accepts a config as follows: my_plugin: definition_file: configs/test.ini # relative to mkdocs.yml validation: enabled: !ENV [CI, false] verbose: true skip_checks: - foo - baz Example import numbers from mkdocs.config import base, config_options as c class _Rectangle(base.Config): width = c.Type(numbers.Real) # required height = c.Type(numbers.Real) # required class MyPluginConfig(base.Config): add_rectangles = c.ListOfItems(c.SubConfig(_Rectangle)) # required In this example we define a list of complex items, and that's achieved by passing a concrete SubConfig to ListOfItems . This accepts a config as follows: my_plugin: add_rectangles: - width: 5 height: 7 - width: 12 height: 2 When the user's configuration is loaded, the above scheme will be used to validate the configuration and fill in any defaults for settings not provided by the user. The validation classes may be any of the classes provided in mkdocs.config.config_options or a third party subclass defined in the plugin. Any settings provided by the user which fail validation or are not defined in the config_scheme will raise a mkdocs.config.base.ValidationError . config A dictionary of configuration options for the plugin, which is populated by the load_config method after configuration validation has completed. Use this attribute to access options provided by the user. def on_pre_build(self, config, **kwargs): if self.config['baz']: # implement "baz" functionality here... New in version 1.4 Safe attribute-based access To get type safety benefits, if you're targeting only MkDocs 1.4+, access options as attributes instead: def on_pre_build(self, config, **kwargs): if self.config.baz: print(self.config.bar ** 2) # OK, `int ** 2` is valid. All BasePlugin subclasses contain the following method(s): load_config(options) Loads configuration from a dictionary of options. Returns a tuple of (errors, warnings) . This method is called by MkDocs during configuration validation and should not need to be called by the plugin. on_<event_name>() Optional methods which define the behavior for specific events . The plugin should define its behavior within these methods. Replace <event_name> with the actual name of the event. For example, the pre_build event would be defined in the on_pre_build method. Most events accept one positional argument and various keyword arguments. It is generally expected that the positional argument would be modified (or replaced) by the plugin and returned. If nothing is returned (the method returns None ), then the original, unmodified object is used. The keyword arguments are simply provided to give context and/or supply data which may be used to determine how the positional argument should be modified. It is good practice to accept keyword arguments as **kwargs . In the event that additional keywords are provided to an event in a future version of MkDocs, there will be no need to alter your plugin. For example, the following event would add an additional static_template to the theme config: class MyPlugin(BasePlugin): def on_config(self, config, **kwargs): config['theme'].static_templates.add('my_template.html') return config New in version 1.4 To get type safety benefits, if you're targeting only MkDocs 1.4+, access config options as attributes instead: def on_config(self, config: MkDocsConfig): config.theme.static_templates.add('my_template.html') return config Events There are three kinds of events: Global Events , Page Events and Template Events . See a diagram with relations between all the plugin events The events themselves are shown in yellow, with their parameters. Arrows show the flow of arguments and outputs of each event. Sometimes they're omitted. The events are chronologically ordered from top to bottom. Dotted lines appear at splits from global events to per-page events. Click the events' titles to jump to their description. MkDocs cluster_on_startup on_startup cluster_build build cluster_on_config on_config cluster_on_pre_build on_pre_build cluster_on_files on_files cluster_on_nav on_nav cluster_populate_page populate_page cluster_on_pre_page on_pre_page cluster_on_page_read_source on_page_read_source cluster_on_page_markdown on_page_markdown cluster_on_page_content on_page_content cluster_on_env on_env cluster_populate_page_2 populate_page cluster_populate_page_3 populate_page cluster_build_page build_page cluster_on_page_context on_page_context cluster_on_post_page on_post_page cluster_build_page_2 build_page cluster_build_page_3 build_page cluster_on_post_build on_post_build cluster_on_serve on_serve cluster_on_shutdown on_shutdown on_startup command dirty load_config load_config on_config config on_pre_build config on_config:s->on_pre_build:n get_files get_files on_config:s->get_files on_files files config on_nav nav config files on_files:s->on_nav:n get_nav get_nav on_files:s->get_nav render_p render pages_point_a on_nav:s->pages_point_a get_context get_context on_nav:s->get_context load_config->on_config:n get_files->on_files:n get_nav->on_nav:n on_pre_page page config files on_page_read_source page config on_pre_page:s->on_page_read_source:n on_page_markdown markdown page config files on_page_read_source:s->on_page_markdown:n on_page_markdown:s->render_p on_page_content html page config files pages_point_b on_page_content:s->pages_point_b on_env env config files render_p->on_page_content:n pages_point_a->on_pre_page:n pages_point_a->render_p placeholder_cluster_populate_page_2 ... pages_point_a->placeholder_cluster_populate_page_2:n placeholder_cluster_populate_page_3 ... pages_point_a->placeholder_cluster_populate_page_3:n placeholder_cluster_populate_page_2:s->pages_point_b pages_point_b->on_env:n pages_point_c pages_point_b->pages_point_c placeholder_cluster_populate_page_3:s->pages_point_b on_env:s->get_context on_page_context context page config nav pages_point_c->on_page_context:n placeholder_cluster_build_page_2 ... pages_point_c->placeholder_cluster_build_page_2:n placeholder_cluster_build_page_3 ... pages_point_c->placeholder_cluster_build_page_3:n render render on_page_context:s->render on_post_page output page config write_file write_file on_post_page:s->write_file get_context->on_page_context:n render->on_post_page:n get_template get_template get_template->render on_post_build config on_serve server config on_shutdown One-time Events One-time events run once per mkdocs invocation. The only case where these tangibly differ from global events is for mkdocs serve : global events, unlike these, will run multiple times -- once per build . on_startup The startup event runs once at the very beginning of an mkdocs invocation. New in MkDocs 1.4. The presence of an on_startup method (even if empty) migrates the plugin to the new system where the plugin object is kept across builds within one mkdocs serve . Note that for initializing variables, the __init__ method is still preferred. For initializing per-build variables (and whenever in doubt), use the on_config event. Parameters: command ( Literal ['build', 'gh-deploy', 'serve'] ) – the command that MkDocs was invoked with, e.g. "serve" for mkdocs serve . dirty ( bool ) – whether --dirty flag was passed. on_shutdown The shutdown event runs once at the very end of an mkdocs invocation, before exiting. This event is relevant only for support of mkdocs serve , otherwise within a single build it's undistinguishable from on_post_build . New in MkDocs 1.4. The presence of an on_shutdown method (even if empty) migrates the plugin to the new system where the plugin object is kept across builds within one mkdocs serve . Note the on_post_build method is still preferred for cleanups, when possible, as it has a much higher chance of actually triggering. on_shutdown is "best effort" because it relies on detecting a graceful shutdown of MkDocs. on_serve The serve event is only called when the serve command is used during development. It runs only once, after the first build finishes. It is passed the Server instance which can be modified before it is activated. For example, additional files or directories could be added to the list of "watched" files for auto-reloading. Parameters: server ( LiveReloadServer ) – livereload.Server instance config ( MkDocsConfig ) – global configuration object builder ( Callable ) – a callable which gets passed to each call to server.watch Returns: LiveReloadServer | None – livereload.Server instance Global Events Global events are called once per build at either the beginning or end of the build process. Any changes made in these events will have a global effect on the entire site. on_config The config event is the first event called on build and is run immediately after the user configuration is loaded and validated. Any alterations to the config should be made here. Parameters: config ( MkDocsConfig ) – global configuration object Returns: MkDocsConfig | None – global configuration object on_pre_build The pre_build event does not alter any variables. Use this event to call pre-build scripts. Parameters: config ( MkDocsConfig ) – global configuration object on_files The files event is called after the files collection is populated from the docs_dir . Use this event to add, remove, or alter files in the collection. Note that Page objects have not yet been associated with the file objects in the collection. Use Page Events to manipulate page specific data. Parameters: files ( Files ) – global files collection config ( MkDocsConfig ) – global configuration object Returns: Files | None – global files collection on_nav The nav event is called after the site navigation is created and can be used to alter the site navigation. Parameters: nav ( Navigation ) – global navigation object config ( MkDocsConfig ) – global configuration object files ( Files ) – global files collection Returns: Navigation | None – global navigation object on_env The env event is called after the Jinja template environment is created and can be used to alter the Jinja environment . Parameters: env ( Environment ) – global Jinja environment config ( MkDocsConfig ) – global configuration object files ( Files ) – global files collection Returns: Environment | None – global Jinja Environment on_post_build The post_build event does not alter any variables. Use this event to call post-build scripts. Parameters: config ( MkDocsConfig ) – global configuration object on_build_error The build_error event is called after an exception of any kind is caught by MkDocs during the build process. Use this event to clean things up before MkDocs terminates. Note that any other events which were scheduled to run after the error will have been skipped. See Handling Errors for more details. Parameters: error ( Exception ) – exception raised Template Events Template events are called once for each non-page template. Each template event will be called for each template defined in the extra_templates config setting as well as any static_templates defined in the theme. All template events are called after the env event and before any page events . on_pre_template The pre_template event is called immediately after the subject template is loaded and can be used to alter the template. Parameters: template ( Template ) – a Jinja2 Template object template_name ( str ) – string filename of template config ( MkDocsConfig ) – global configuration object Returns: Template | None – a Jinja2 Template object on_template_context The template_context event is called immediately after the context is created for the subject template and can be used to alter the context for that specific template only. Parameters: context ( TemplateContext ) – dict of template context variables template_name ( str ) – string filename of template config ( MkDocsConfig ) – global configuration object Returns: TemplateContext | None – dict of template context variables on_post_template The post_template event is called after the template is rendered, but before it is written to disc and can be used to alter the output of the template. If an empty string is returned, the template is skipped and nothing is is written to disc. Parameters: output_content ( str ) – output of rendered template as string template_name ( str ) – string filename of template config ( MkDocsConfig ) – global configuration object Returns: str | None – output of rendered template as string Page Events Page events are called once for each Markdown page included in the site. All page events are called after the post_template event and before the post_build event. on_pre_page The pre_page event is called before any actions are taken on the subject page and can be used to alter the Page instance. Parameters: page ( Page ) – mkdocs.structure.pages.Page instance config ( MkDocsConfig ) – global configuration object files ( Files ) – global files collection Returns: Page | None – mkdocs.structure.pages.Page instance on_page_read_source Deprecated Instead of this event, prefer one of these alternatives: Since MkDocs 1.6, instead set content_bytes / content_string of a File inside on_files . Usually (although it's not an exact alternative), on_page_markdown can serve the same purpose. The on_page_read_source event can replace the default mechanism to read the contents of a page's source from the filesystem. Parameters: page ( Page ) – mkdocs.structure.pages.Page instance config ( MkDocsConfig ) – global configuration object Returns: str | None – The raw source for a page as unicode string. If None is returned, the default loading from a file will be performed. on_page_markdown The page_markdown event is called after the page's markdown is loaded from file and can be used to alter the Markdown source text. The meta- data has been stripped off and is available as page.meta at this point. Parameters: markdown ( str ) – Markdown source text of page as string page ( Page ) – mkdocs.structure.pages.Page instance config ( MkDocsConfig ) – global configuration object files ( Files ) – global files collection Returns: str | None – Markdown source text of page as string on_page_content The page_content event is called after the Markdown text is rendered to HTML (but before being passed to a template) and can be used to alter the HTML body of the page. Parameters: html ( str ) – HTML rendered from Markdown source as string page ( Page ) – mkdocs.structure.pages.Page instance config ( MkDocsConfig ) – global configuration object files ( Files ) – global files collection Returns: str | None – HTML rendered from Markdown source as string on_page_context The page_context event is called after the context for a page is created and can be used to alter the context for that specific page only. Parameters: context ( TemplateContext ) – dict of template context variables page ( Page ) – mkdocs.structure.pages.Page instance config ( MkDocsConfig ) – global configuration object nav ( Navigation ) – global navigation object Returns: TemplateContext | None – dict of template context variables on_post_page The post_page event is called after the template is rendered, but before it is written to disc and can be used to alter the output of the page. If an empty string is returned, the page is skipped and nothing is written to disc. Parameters: output ( str ) – output of rendered template as string page ( Page ) – mkdocs.structure.pages.Page instance config ( MkDocsConfig ) – global configuration object Returns: str | None – output of rendered template as string Event Priorities For each event type, corresponding methods of plugins are called in the order that the plugins appear in the plugins config . Since MkDocs 1.4, plugins can choose to set a priority value for their events. Events with higher priority are called first. Events without a chosen priority get a default of 0. Events that have the same priority are ordered as they appear in the config. mkdocs.plugins.event_priority(priority: float) -> Callable[[T], T] A decorator to set an event priority for an event handler method. Recommended priority values: 100 "first", 50 "early", 0 "default", -50 "late", -100 "last". As different plugins discover more precise relations to each other, the values should be further tweaked. Usage example: @plugins.event_priority(-100) # Wishing to run this after all other plugins' `on_files` events. def on_files(self, files, config, **kwargs): ... New in MkDocs 1.4. Recommended shim for backwards compatibility: try: from mkdocs.plugins import event_priority except ImportError: event_priority = lambda priority: lambda f: f # No-op fallback New in version 1.6 There may also arise a need to register a handler for the same event at multiple different priorities. CombinedEvent makes this possible. mkdocs.plugins.CombinedEvent Bases: Generic [ P , T ] A descriptor that allows defining multiple event handlers and declaring them under one event's name. Usage example: @plugins.event_priority(100) def _on_page_markdown_1(self, markdown: str, **kwargs): ... @plugins.event_priority(-50) def _on_page_markdown_2(self, markdown: str, **kwargs): ... on_page_markdown = plugins.CombinedEvent(_on_page_markdown_1, _on_page_markdown_2) Note The names of the sub-methods can't start with on_ ; instead they can start with _on_ like in the the above example, or anything else. Handling Errors MkDocs defines four error types: mkdocs.exceptions.MkDocsException Bases: ClickException The base class which all MkDocs exceptions inherit from. This should not be raised directly. One of the subclasses should be raised instead. mkdocs.exceptions.ConfigurationError Bases: MkDocsException This error is raised by configuration validation when a validation error is encountered. This error should be raised by any configuration options defined in a plugin's config_scheme . mkdocs.exceptions.BuildError Bases: MkDocsException This error may be raised by MkDocs during the build process. Plugins should not raise this error. mkdocs.exceptions.PluginError Bases: BuildError A subclass of mkdocs.exceptions.BuildError which can be raised by plugin events. Unexpected and uncaught exceptions will interrupt the build process and produce typical Python tracebacks, which are useful for debugging your code. However, users generally find tracebacks overwhelming and often miss the helpful error message. Therefore, MkDocs will catch any of the errors listed above, retrieve the error message, and exit immediately with only the helpful message displayed to the user. Therefore, you might want to catch any exceptions within your plugin and raise a PluginError , passing in your own custom-crafted message, so that the build process is aborted with a helpful message. The on_build_error event will be triggered for any exception. For example: from mkdocs.exceptions import PluginError from mkdocs.plugins import BasePlugin class MyPlugin(BasePlugin): def on_post_page(self, output, page, config, **kwargs): try: # some code that could throw a KeyError ... except KeyError as error: raise PluginError(f"Failed to find the item by key: '{error}'") def on_build_error(self, error, **kwargs): # some code to clean things up ... Logging in plugins To ensure that your plugins' log messages adhere with MkDocs' formatting and --verbose / --debug flags, please write the logs to a logger under the mkdocs.plugins. namespace. Example import logging log = logging.getLogger(f"mkdocs.plugins.{__name__}") log.warning("File '%s' not found. Breaks the build if --strict is passed", my_file_name) log.info("Shown normally") log.debug("Shown only with `--verbose`") if log.getEffectiveLevel() <= logging.DEBUG: log.debug("Very expensive calculation only for debugging: %s", get_my_diagnostics()) log.error() is another logging level that is differentiated by its look, but in all other ways it functions the same as warning , so it's strange to use it. If your plugin encounters an actual error, it is best to just interrupt the build by raising mkdocs.exceptions.PluginError (which will also log an ERROR message). New in version 1.5 MkDocs now provides a get_plugin_logger() convenience function that returns a logger like the above that is also prefixed with the plugin's name. mkdocs.plugins.get_plugin_logger(name: str) -> PrefixedLogger Return a logger for plugins. Parameters: name ( str ) – The name to use with logging.getLogger . Returns: PrefixedLogger – A logger configured to work well in MkDocs, prefixing each message with the plugin package name. Example from mkdocs.plugins import get_plugin_logger log = get_plugin_logger(__name__) log.info("My plugin message") Entry Point Plugins need to be packaged as Python libraries (distributed on PyPI separate from MkDocs) and each must register as a Plugin via a setuptools entry_points . Add the following to your setup.py script: entry_points={ 'mkdocs.plugins': [ 'pluginname = path.to.some_plugin:SomePluginClass', ] } The pluginname would be the name used by users (in the config file) and path.to.some_plugin:SomePluginClass would be the importable plugin itself ( from path.to.some_plugin import SomePluginClass ) where SomePluginClass is a subclass of BasePlugin which defines the plugin behavior. Naturally, multiple Plugin classes could exist in the same module. Simply define each as a separate entry point. entry_points={ 'mkdocs.plugins': [ 'featureA = path.to.my_plugins:PluginA', 'featureB = path.to.my_plugins:PluginB' ] } Note that registering a plugin does not activate it. The user still needs to tell MkDocs to use it via the config. Publishing a Plugin You should publish a package on PyPI , then add it to the Catalog for discoverability. Plugins are strongly recommended to have a unique plugin name (entry point name) according to the catalog. 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://rust-lang.github.io/api-guidelines/documentation.html#release-notes-document-all-significant-changes-c-relnotes | Documentation - 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 Documentation Crate level docs are thorough and include examples (C-CRATE-DOC) See RFC 1687 . All items have a rustdoc example (C-EXAMPLE) Every public module, trait, struct, enum, function, method, macro, and type definition should have an example that exercises the functionality. This guideline should be applied within reason. A link to an applicable example on another item may be sufficient. For example if exactly one function uses a particular type, it may be appropriate to write a single example on either the function or the type and link to it from the other. The purpose of an example is not always to show how to use the item. Readers can be expected to understand how to invoke functions, match on enums, and other fundamental tasks. Rather, an example is often intended to show why someone would want to use the item. // This would be a poor example of using clone(). It mechanically shows *how* to // call clone(), but does nothing to show *why* somebody would want this. fn main() { let hello = "hello"; hello.clone(); } Examples use ? , not try! , not unwrap (C-QUESTION-MARK) Like it or not, example code is often copied verbatim by users. Unwrapping an error should be a conscious decision that the user needs to make. A common way of structuring fallible example code is the following. The lines beginning with # are compiled by cargo test when building the example but will not appear in user-visible rustdoc. /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box<dyn Error>> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` Function docs include error, panic, and safety considerations (C-FAILURE) Error conditions should be documented in an "Errors" section. This applies to trait methods as well -- trait methods for which the implementation is allowed or expected to return an error should be documented with an "Errors" section. For example in the standard library, Some implementations of the std::io::Read::read trait method may return an error. /// Pull some bytes from this source into the specified buffer, returning /// how many bytes were read. /// /// ... lots more info ... /// /// # Errors /// /// If this function encounters any form of I/O or other error, an error /// variant will be returned. If an error is returned then it must be /// guaranteed that no bytes were read. Panic conditions should be documented in a "Panics" section. This applies to trait methods as well -- traits methods for which the implementation is allowed or expected to panic should be documented with a "Panics" section. In the standard library the Vec::insert method may panic. /// Inserts an element at position `index` within the vector, shifting all /// elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. It is not necessary to document all conceivable panic cases, especially if the panic occurs in logic provided by the caller. For example documenting the Display panic in the following code seems excessive. But when in doubt, err on the side of documenting more panic cases. #![allow(unused)] fn main() { /// # Panics /// /// This function panics if `T`'s implementation of `Display` panics. pub fn print<T: Display>(t: T) { println!("{}", t.to_string()); } } Unsafe functions should be documented with a "Safety" section that explains all invariants that the caller is responsible for upholding to use the function correctly. The unsafe std::ptr::read requires the following of the caller. /// Reads the value from `src` without moving it. This leaves the /// memory in `src` unchanged. /// /// # Safety /// /// Beyond accepting a raw pointer, this is unsafe because it semantically /// moves the value out of `src` without preventing further usage of `src`. /// If `T` is not `Copy`, then care must be taken to ensure that the value at /// `src` is not used before the data is overwritten again (e.g. with `write`, /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use /// because it will attempt to drop the value previously at `*src`. /// /// The pointer must be aligned; use `read_unaligned` if that is not the case. Prose contains hyperlinks to relevant things (C-LINK) Regular links can be added inline with the usual markdown syntax of [text](url) . Links to other types can be added by marking them with [`text`] , then adding the link target in a new line at the end of the docstring with [`text`]: <target> , where <target> is described below. Link targets to methods within the same type usually look like this: [`serialize_struct`]: #method.serialize_struct Link targets to other types usually look like this: [`Deserialize`]: trait.Deserialize.html Link targets may also point to a parent or child module: [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html This guideline is officially recommended by RFC 1574 under the heading "Link all the things" . Cargo.toml includes all common metadata (C-METADATA) The [package] section of Cargo.toml should include the following values: authors description license repository keywords categories In addition, there are two optional metadata fields: documentation homepage By default, crates.io links to documentation for the crate on docs.rs . The documentation metadata only needs to be set if the documentation is hosted somewhere other than docs.rs , for example because the crate links against a shared library that is not available in the build environment of docs.rs . The homepage metadata should only be set if there is a unique website for the crate other than the source repository or API documentation. Do not make homepage redundant with either the documentation or repository values. For example, serde sets homepage to https://serde.rs , a dedicated website. Release notes document all significant changes (C-RELNOTES) Users of the crate can read the release notes to find a summary of what changed in each published release of the crate. A link to the release notes, or the notes themselves, should be included in the crate-level documentation and/or the repository linked in Cargo.toml. Breaking changes (as defined in RFC 1105 ) should be clearly identified in the release notes. If using Git to track the source of a crate, every release published to crates.io should have a corresponding tag identifying the commit that was published. A similar process should be used for non-Git VCS tools as well. # Tag the current commit GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 git push --tags Annotated tags are preferred because some Git commands ignore unannotated tags if any annotated tags exist. Examples Serde 1.0.0 release notes Serde 0.9.8 release notes Serde 0.9.0 release notes Diesel change log Rustdoc does not show unhelpful implementation details (C-HIDDEN) Rustdoc is supposed to include everything users need to use the crate fully and nothing more. It is fine to explain relevant implementation details in prose but they should not be real entries in the documentation. Especially be selective about which impls are visible in rustdoc -- all the ones that users would need for using the crate fully, but no others. In the following code the rustdoc of PublicError by default would show the From<PrivateError> impl. We choose to hide it with #[doc(hidden)] because users can never have a PrivateError in their code so this impl would never be relevant to them. #![allow(unused)] fn main() { // This error type is returned to users. pub struct PublicError { /* ... */ } // This error type is returned by some private helper functions. struct PrivateError { /* ... */ } // Enable use of `?` operator. #[doc(hidden)] impl From<PrivateError> for PublicError { fn from(err: PrivateError) -> PublicError { /* ... */ } } } pub(crate) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate. | 2026-01-13T09:29:13 |
https://doc.rust-lang.org/cargo/reference/features-examples.html | Features Examples - 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 Features Examples The following illustrates some real-world examples of features in action. Minimizing build times and file sizes Some packages use features so that if the features are not enabled, it reduces the size of the crate and reduces compile time. Some examples are: syn is a popular crate for parsing Rust code. Since it is so popular, it is helpful to reduce compile times since it affects so many projects. It has a clearly documented list of features which can be used to minimize the amount of code it contains. regex has a several features that are well documented . Cutting out Unicode support can reduce the resulting file size as it can remove some large tables. winapi has a large number of features that limit which Windows API bindings it supports. web-sys is another example similar to winapi that provides a huge surface area of API bindings that are limited by using features. Extending behavior The serde_json package has a preserve_order feature which changes the behavior of JSON maps to preserve the order that keys are inserted. Notice that it enables an optional dependency indexmap to implement the new behavior. When changing behavior like this, be careful to make sure the changes are SemVer compatible . That is, enabling the feature should not break code that usually builds with the feature off. no_std support Some packages want to support both no_std and std environments. This is useful for supporting embedded and resource-constrained platforms, but still allowing extended capabilities for platforms that support the full standard library. The wasm-bindgen package defines a std feature that is enabled by default . At the top of the library, it unconditionally enables the no_std attribute . This ensures that std and the std prelude are not automatically in scope. Then, in various places in the code ( example1 , example2 ), it uses #[cfg(feature = "std")] attributes to conditionally enable extra functionality that requires std . Re-exporting dependency features It can be convenient to re-export the features from a dependency. This allows the user depending on the crate to control those features without needing to specify those dependencies directly. For example, regex re-exports the features from the regex_syntax package. Users of regex don’t need to know about the regex_syntax package, but they can still access the features it contains. Vendoring of C libraries Some packages provide bindings to common C libraries (sometimes referred to as “sys” crates ). Sometimes these packages give you the choice to use the C library installed on the system, or to build it from source. For example, the openssl package has a vendored feature which enables the corresponding vendored feature of openssl-sys . The openssl-sys build script has some conditional logic which causes it to build from a local copy of the OpenSSL source code instead of using the version from the system. The curl-sys package is another example where the static-curl feature causes it to build libcurl from source. Notice that it also has a force-system-lib-on-osx feature which forces it to use the system libcurl , overriding the static-curl setting. Feature precedence Some packages may have mutually-exclusive features. One option to handle this is to prefer one feature over another. The log package is an example. It has several features for choosing the maximum logging level at compile-time described here . It uses cfg-if to choose a precedence . If multiple features are enabled, the higher “max” levels will be preferred over the lower levels. Proc-macro companion package Some packages have a proc-macro that is intimately tied with it. However, not all users will need to use the proc-macro. By making the proc-macro an optional-dependency, this allows you to conveniently choose whether or not it is included. This is helpful, because sometimes the proc-macro version must stay in sync with the parent package, and you don’t want to force the users to have to specify both dependencies and keep them in sync. An example is serde which has a derive feature which enables the serde_derive proc-macro. The serde_derive crate is very tightly tied to serde , so it uses an equals version requirement to ensure they stay in sync. Nightly-only features Some packages want to experiment with APIs or language features that are only available on the Rust nightly channel . However, they may not want to require their users to also use the nightly channel. An example is wasm-bindgen which has a nightly feature which enables an extended API that uses the Unsize marker trait that is only available on the nightly channel at the time of this writing. Note that at the root of the crate it uses cfg_attr to enable the nightly feature . Keep in mind that the feature attribute is unrelated to Cargo features, and is used to opt-in to experimental language features. The simd_support feature of the rand package is another example, which relies on a dependency that only builds on the nightly channel. Experimental features Some packages have new functionality that they may want to experiment with, without having to commit to the stability of those APIs. The features are usually documented that they are experimental, and thus may change or break in the future, even during a minor release. An example is the async-std package, which has an unstable feature , which gates new APIs that people can opt-in to using, but may not be completely ready to be relied upon. | 2026-01-13T09:29:13 |
https://ja-jp.facebook.com/reg/?entry_point=login&amp%3Bnext=https%3A%2F%2Fwww.facebook.com%2Fshare_channel%2F%3Ftype%3Dreshare%26link%3Dhttps%253A%252F%252Fdev.to%252Ftauri%252Ftauri-10-release-candidate-53jk%26app_id%3D966242223397117%26source_surface%3Dexternal_reshare%26display%26hashtag | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.