Skip to content

Instantly share code, notes, and snippets.

@MultisampledNight
Created June 10, 2022 17:11
Show Gist options
  • Save MultisampledNight/7069f686b2d6b8755c5d6448a1f5d80d to your computer and use it in GitHub Desktop.
Save MultisampledNight/7069f686b2d6b8755c5d6448a1f5d80d to your computer and use it in GitHub Desktop.
LSP log upon random error in NeoVim (see rust-lang/rust-analyzer#12482)
[ERROR][2022-06-10 19:05:30] .../vim/lsp/rpc.lua:534 "No callback found for server response id 3"
[ERROR][2022-06-10 19:05:30] .../lua/vim/lsp.lua:824 "LSP[rust_analyzer]" "on_error" { code = "NO_RESULT_CALLBACK_FOUND", err = { id = 3, jsonrpc = "2.0", result = { isIncomplete = true, items = { { additionalTextEdits = {}, deprecated = false, filterText = "self::", kind = 14, label = "self::", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "self::", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "super::", kind = 14, label = "super::", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "super::", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "crate::", kind = 14, label = "crate::", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "crate::", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "MacroConfig", kind = 22, label = "MacroConfig", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "MacroConfig", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Error returned when a Syn parser cannot parse the input tokens.\n\n# Error reporting in proc macros\n\nThe correct way to report errors back to the compiler from a procedural\nmacro is by emitting an appropriately spanned invocation of\n[`compile_error!`] in the generated code. This produces a better diagnostic\nmessage than simply panicking the macro.\n\n[`compile_error!`]: std::compile_error!\n\nWhen parsing macro input, the [`parse_macro_input!`] macro handles the\nconversion to `compile_error!` automatically.\n\n```rust\nuse proc_macro::TokenStream;\nuse syn::{parse_macro_input, AttributeArgs, ItemFn};\n\n#[proc_macro_attribute]\npub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream {\n let args = parse_macro_input!(args as AttributeArgs);\n let input = parse_macro_input!(input as ItemFn);\n\n /* ... */\n}\n```\n\nFor errors that arise later than the initial parsing stage, the\n[`.to_compile_error()`] or [`.into_compile_error()`] methods can be used to\nperform an explicit conversion to `compile_error!`.\n\n[`.to_compile_error()`]: Error::to_compile_error\n[`.into_compile_error()`]: Error::into_compile_error\n\n```rust\n#[proc_macro_derive(MyDerive)]\npub fn my_derive(input: TokenStream) -> TokenStream {\n let input = parse_macro_input!(input as DeriveInput);\n\n // fn(DeriveInput) -> syn::Result<proc_macro2::TokenStream>\n expand::my_derive(input)\n .unwrap_or_else(syn::Error::into_compile_error)\n .into()\n}\n```" }, filterText = "Error", kind = 22, label = "Error", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Error", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! parse_macro_input", documentation = { kind = "markdown", value = "Parse the input TokenStream of a macro, triggering a compile error if the\ntokens fail to parse.\n\nRefer to the [`parse` module] documentation for more details about parsing\nin Syn.\n\n[`parse` module]: crate::rustdoc_workaround::parse_module\n\n<br>\n\n# Intended usage\n\nThis macro must be called from a function that returns\n`proc_macro::TokenStream`. Usually this will be your proc macro entry point,\nthe function that has the #\\[proc_macro\\] / #\\[proc_macro_derive\\] /\n#\\[proc_macro_attribute\\] attribute.\n\n```rust\nuse proc_macro::TokenStream;\nuse syn::{parse_macro_input, Result};\nuse syn::parse::{Parse, ParseStream};\n\nstruct MyMacroInput {\n /* ... */\n}\n\nimpl Parse for MyMacroInput {\n fn parse(input: ParseStream) -> Result<Self> {\n /* ... */\n }\n}\n\n#[proc_macro]\npub fn my_macro(tokens: TokenStream) -> TokenStream {\n let input = parse_macro_input!(tokens as MyMacroInput);\n\n /* ... */\n}\n```\n\n<br>\n\n# Usage with Parser\n\nThis macro can also be used with the [`Parser` trait] for types that have\nmultiple ways that they can be parsed.\n\n[`Parser` trait]: crate::rustdoc_workaround::parse_module::Parser\n\n```rust\nimpl MyMacroInput {\n fn parse_alternate(input: ParseStream) -> Result<Self> {\n /* ... */\n }\n}\n\n#[proc_macro]\npub fn my_macro(tokens: TokenStream) -> TokenStream {\n let input = parse_macro_input!(tokens with MyMacroInput::parse_alternate);\n\n /* ... */\n}\n```\n\n<br>\n\n# Expansion\n\n`parse_macro_input!($variable as $Type)` expands to something like:\n\n```rust\nmatch syn::parse::<$Type>($variable) {\n Ok(syntax_tree) => syntax_tree,\n Err(err) => return proc_macro::TokenStream::from(err.to_compile_error()),\n}\n```" }, filterText = "parse_macro_input!", insertTextFormat = 2, kind = 3, label = "parse_macro_input!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "parse_macro_input!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = 'A free-standing function: `fn process(n: usize) -> Result<()> { ...\n}`.\n\n*This type is available only if Syn is built with the `"full"` feature.*' }, filterText = "ItemFn", kind = 22, label = "ItemFn", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "ItemFn", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "The main type provided by this crate, representing an abstract stream of\ntokens, or, more specifically, a sequence of token trees.\nThe type provide interfaces for iterating over those token trees and, conversely,\ncollecting a number of token trees into one stream.\n\nThis is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`\nand `#[proc_macro_derive]` definitions." }, filterText = "TokenStream", kind = 22, label = "TokenStream", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "TokenStream", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "parse", kind = 9, label = "parse", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "parse", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "proc_macro collect_callbacks", filterText = "collect_callbacks!", insertTextFormat = 2, kind = 3, label = "collect_callbacks!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "collect_callbacks!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! quote", filterText = "quote!", insertTextFormat = 2, kind = 3, label = "quote!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "quote!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "[![github]](https://github.com/dtolnay/quote)&ensp;[![crates-io]](https://crates.io/crates/quote)&ensp;[![docs-rs]](https://docs.rs/quote)\n\n[github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github\n[crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust\n[docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K\n\n<br>\n\nThis crate provides the [`quote!`] macro for turning Rust syntax tree data\nstructures into tokens of source code.\n\n[`quote!`]: macro.quote.html\n\nProcedural macros in Rust receive a stream of tokens as input, execute\narbitrary Rust code to determine how to manipulate those tokens, and produce\na stream of tokens to hand back to the compiler to compile into the caller's\ncrate. Quasi-quoting is a solution to one piece of that &mdash; producing\ntokens to return to the compiler.\n\nThe idea of quasi-quoting is that we write *code* that we treat as *data*.\nWithin the `quote!` macro, we can write what looks like code to our text\neditor or IDE. We get all the benefits of the editor's brace matching,\nsyntax highlighting, indentation, and maybe autocompletion. But rather than\ncompiling that as code into the current crate, we can treat it as data, pass\nit around, mutate it, and eventually hand it back to the compiler as tokens\nto compile into the macro caller's crate.\n\nThis crate is motivated by the procedural macro use case, but is a\ngeneral-purpose Rust quasi-quoting library and is not specific to procedural\nmacros.\n\n```toml\n[dependencies]\nquote = \"1.0\"\n```\n\n<br>\n\n# Example\n\nThe following quasi-quoted block of code is something you might find in [a]\nprocedural macro having to do with data structure serialization. The `#var`\nsyntax performs interpolation of runtime variables into the quoted tokens.\nCheck out the documentation of the [`quote!`] macro for more detail about\nthe syntax. See also the [`quote_spanned!`] macro which is important for\nimplementing hygienic procedural macros.\n\n[a]: https://serde.rs/\n[`quote_spanned!`]: macro.quote_spanned.html\n\n```rust\nlet tokens = quote! {\n struct SerializeWith #generics #where_clause {\n value: &'a #field_ty,\n phantom: core::marker::PhantomData<#item_ty>,\n }\n\n impl #generics serde::Serialize for SerializeWith #generics #where_clause {\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n where\n S: serde::Serializer,\n {\n #path(self.value, serializer)\n }\n }\n\n SerializeWith {\n value: #value,\n phantom: core::marker::PhantomData::<#item_ty>,\n }\n};\n```" }, filterText = "quote", kind = 9, label = "quote", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "quote", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = 'Return type of a function signature.\n\n*This type is available only if Syn is built with the `"derive"` or `"full"`\nfeature.*' }, filterText = "ReturnType", kind = 13, label = "ReturnType", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "ReturnType", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "Context", kind = 22, label = "Context", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Context", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! eprint", documentation = { kind = "markdown", value = 'Prints to the standard error.\n\nEquivalent to the [`print!`] macro, except that output goes to\n[`io::stderr`] instead of [`io::stdout`]. See [`print!`] for\nexample usage.\n\nUse `eprint!` only for error and progress messages. Use `print!`\ninstead for the primary output of your program.\n\n[`io::stderr`]: crate::io::stderr\n[`io::stdout`]: crate::io::stdout\n\n# Panics\n\nPanics if writing to `io::stderr` fails.\n\n# Examples\n\n```rust\neprint!("Error: Could not complete task");\n```' }, filterText = "eprint!", insertTextFormat = 2, kind = 3, label = "eprint!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "eprint!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! panic", filterText = "panic!", insertTextFormat = 2, kind = 3, label = "panic!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "panic!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! debug_assert_eq", documentation = { kind = "markdown", value = "Asserts that two expressions are equal to each other.\n\nOn panic, this macro will print the values of the expressions with their\ndebug representations.\n\nUnlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non\noptimized builds by default. An optimized build will not execute\n`debug_assert_eq!` statements unless `-C debug-assertions` is passed to the\ncompiler. This makes `debug_assert_eq!` useful for checks that are too\nexpensive to be present in a release build but may be helpful during\ndevelopment. The result of expanding `debug_assert_eq!` is always type checked.\n\n# Examples\n\n```rust\nlet a = 3;\nlet b = 1 + 2;\ndebug_assert_eq!(a, b);\n```" }, filterText = "debug_assert_eq!", insertTextFormat = 2, kind = 3, label = "debug_assert_eq!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "debug_assert_eq!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! stringify", documentation = { kind = "markdown", value = "Stringifies its arguments.\n\nThis macro will yield an expression of type `&'static str` which is the\nstringification of all the tokens passed to the macro. No restrictions\nare placed on the syntax of the macro invocation itself.\n\nNote that the expanded results of the input tokens may change in the\nfuture. You should be careful if you rely on the output.\n\n# Examples\n\n```rust\nlet one_plus_one = stringify!(1 + 1);\nassert_eq!(one_plus_one, \"1 + 1\");\n```" }, filterText = "stringify!", insertTextFormat = 2, kind = 3, label = "stringify!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "stringify!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! concat", documentation = { kind = "markdown", value = "Concatenates literals into a static string slice.\n\nThis macro takes any number of comma-separated literals, yielding an\nexpression of type `&'static str` which represents all of the literals\nconcatenated left-to-right.\n\nInteger and floating point literals are stringified in order to be\nconcatenated.\n\n# Examples\n\n```rust\nlet s = concat!(\"test\", 10, 'b', true);\nassert_eq!(s, \"test10btrue\");\n```" }, filterText = "concat!", insertTextFormat = 2, kind = 3, label = "concat!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "concat!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! format", documentation = { kind = "markdown", value = 'Creates a `String` using interpolation of runtime expressions.\n\nThe first argument `format!` receives is a format string. This must be a string\nliteral. The power of the formatting string is in the `{}`s contained.\n\nAdditional parameters passed to `format!` replace the `{}`s within the\nformatting string in the order given unless named or positional parameters\nare used; see [`std::fmt`] for more information.\n\nA common use for `format!` is concatenation and interpolation of strings.\nThe same convention is used with [`print!`] and [`write!`] macros,\ndepending on the intended destination of the string.\n\nTo convert a single value to a string, use the [`to_string`] method. This\nwill use the [`Display`] formatting trait.\n\n[`std::fmt`]: ../std/fmt/index.html\n[`print!`]: ../std/macro.print.html\n[`write!`]: core::write\n[`to_string`]: crate::string::ToString\n[`Display`]: core::fmt::Display\n\n# Panics\n\n`format!` panics if a formatting trait implementation returns an error.\nThis indicates an incorrect implementation\nsince `fmt::Write for String` never returns an error itself.\n\n# Examples\n\n```rust\nformat!("test");\nformat!("hello {}", "world!");\nformat!("x = {}, y = {y}", 10, y = 30);\n```' }, filterText = "format!", insertTextFormat = 2, kind = 3, label = "format!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "format!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! log_syntax", documentation = { kind = "markdown", value = "Prints passed tokens into the standard output." }, filterText = "log_syntax!", insertTextFormat = 2, kind = 3, label = "log_syntax!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "log_syntax!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! include_str", documentation = { kind = "markdown", value = "Includes a UTF-8 encoded file as a string.\n\nThe file is located relative to the current file (similarly to how\nmodules are found). The provided path is interpreted in a platform-specific\nway at compile time. So, for instance, an invocation with a Windows path\ncontaining backslashes `\\` would not compile correctly on Unix.\n\nThis macro will yield an expression of type `&'static str` which is the\ncontents of the file.\n\n# Examples\n\nAssume there are two files in the same directory with the following\ncontents:\n\nFile 'spanish.in':\n\n```text\nadiós\n```\n\nFile 'main.rs':\n\n```rust\nfn main() {\n let my_str = include_str!(\"spanish.in\");\n assert_eq!(my_str, \"adiós\\n\");\n print!(\"{my_str}\");\n}\n```\n\nCompiling 'main.rs' and running the resulting binary will print \"adiós\"." }, filterText = "include_str!", insertTextFormat = 2, kind = 3, label = "include_str!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "include_str!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! assert_ne", documentation = { kind = "markdown", value = 'Asserts that two expressions are not equal to each other (using [`PartialEq`]).\n\nOn panic, this macro will print the values of the expressions with their\ndebug representations.\n\nLike [`assert!`], this macro has a second form, where a custom\npanic message can be provided.\n\n# Examples\n\n```rust\nlet a = 3;\nlet b = 2;\nassert_ne!(a, b);\n\nassert_ne!(a, b, "we are testing that the values are not equal");\n```' }, filterText = "assert_ne!", insertTextFormat = 2, kind = 3, label = "assert_ne!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "assert_ne!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! dbg", documentation = { kind = "markdown", value = "Prints and returns the value of a given expression for quick and dirty\ndebugging.\n\nAn example:\n\n```rust\nlet a = 2;\nlet b = dbg!(a * 2) + 1;\n// ^-- prints: [src/main.rs:2] a * 2 = 4\nassert_eq!(b, 5);\n```\n\nThe macro works by using the `Debug` implementation of the type of\nthe given expression to print the value to [stderr] along with the\nsource location of the macro invocation as well as the source code\nof the expression.\n\nInvoking the macro on an expression moves and takes ownership of it\nbefore returning the evaluated expression unchanged. If the type\nof the expression does not implement `Copy` and you don't want\nto give up ownership, you can instead borrow with `dbg!(&expr)`\nfor some expression `expr`.\n\nThe `dbg!` macro works exactly the same in release builds.\nThis is useful when debugging issues that only occur in release\nbuilds or when debugging in release mode is significantly faster.\n\nNote that the macro is intended as a debugging tool and therefore you\nshould avoid having uses of it in version control for long periods\n(other than in tests and similar).\nDebug output from production code is better done with other facilities\nsuch as the [`debug!`] macro from the [`log`] crate.\n\n# Stability\n\nThe exact output printed by this macro should not be relied upon\nand is subject to future changes.\n\n# Panics\n\nPanics if writing to `io::stderr` fails.\n\n# Further examples\n\nWith a method call:\n\n```rust\nfn foo(n: usize) {\n if let Some(_) = dbg!(n.checked_sub(4)) {\n // ...\n }\n}\n\nfoo(3)\n```\n\nThis prints to [stderr]:\n\n```text,ignore\n[src/main.rs:4] n.checked_sub(4) = None\n```\n\nNaive factorial implementation:\n\n```rust\nfn factorial(n: u32) -> u32 {\n if dbg!(n <= 1) {\n dbg!(1)\n } else {\n dbg!(n * factorial(n - 1))\n }\n}\n\ndbg!(factorial(4));\n```\n\nThis prints to [stderr]:\n\n```text,ignore\n[src/main.rs:3] n <= 1 = false\n[src/main.rs:3] n <= 1 = false\n[src/main.rs:3] n <= 1 = false\n[src/main.rs:3] n <= 1 = true\n[src/main.rs:4] 1 = 1\n[src/main.rs:5] n * factorial(n - 1) = 2\n[src/main.rs:5] n * factorial(n - 1) = 6\n[src/main.rs:5] n * factorial(n - 1) = 24\n[src/main.rs:11] factorial(4) = 24\n```\n\nThe `dbg!(..)` macro moves the input:\n\n```rust\n/// A wrapper around `usize` which importantly is not Copyable.\n#[derive(Debug)]\nstruct NoCopy(usize);\n\nlet a = NoCopy(42);\nlet _ = dbg!(a); // <-- `a` is moved here.\nlet _ = dbg!(a); // <-- `a` is moved again; error!\n```\n\nYou can also use `dbg!()` without a value to just print the\nfile and line whenever it's reached.\n\nFinally, if you want to `dbg!(..)` multiple values, it will treat them as\na tuple (and return it, too):\n\n```rust\nassert_eq!(dbg!(1usize, 2u32), (1, 2));\n```\n\nHowever, a single argument with a trailing comma will still not be treated\nas a tuple, following the convention of ignoring trailing commas in macro\ninvocations. You can use a 1-tuple directly if you need one:\n\n```rust\nassert_eq!(1, dbg!(1u32,)); // trailing comma ignored\nassert_eq!((1,), dbg!((1u32,))); // 1-tuple\n```\n\n[stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)\n[`debug!`]: https://docs.rs/log/*/log/macro.debug.html\n[`log`]: https://crates.io/crates/log" }, filterText = "dbg!", insertTextFormat = 2, kind = 3, label = "dbg!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "dbg!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! vec", documentation = { kind = "markdown", value = "Creates a [`Vec`] containing the arguments.\n\n`vec!` allows `Vec`s to be defined with the same syntax as array expressions.\nThere are two forms of this macro:\n\n- Create a [`Vec`] containing a given list of elements:\n\n```rust\nlet v = vec![1, 2, 3];\nassert_eq!(v[0], 1);\nassert_eq!(v[1], 2);\nassert_eq!(v[2], 3);\n```\n\n- Create a [`Vec`] from a given element and size:\n\n```rust\nlet v = vec![1; 3];\nassert_eq!(v, [1, 1, 1]);\n```\n\nNote that unlike array expressions this syntax supports all elements\nwhich implement [`Clone`] and the number of elements doesn't have to be\na constant.\n\nThis will use `clone` to duplicate an expression, so one should be careful\nusing this with types having a nonstandard `Clone` implementation. For\nexample, `vec![Rc::new(1); 5]` will create a vector of five references\nto the same boxed integer value, not five references pointing to independently\nboxed integers.\n\nAlso, note that `vec![expr; 0]` is allowed, and produces an empty vector.\nThis will still evaluate `expr`, however, and immediately drop the resulting value, so\nbe mindful of side effects.\n\n[`Vec`]: crate::vec::Vec" }, filterText = "vec!", insertTextFormat = 2, kind = 3, label = "vec![…]", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "vec![$0]", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! include", documentation = { kind = "markdown", value = "Parses a file as an expression or an item according to the context.\n\nThe file is located relative to the current file (similarly to how\nmodules are found). The provided path is interpreted in a platform-specific\nway at compile time. So, for instance, an invocation with a Windows path\ncontaining backslashes `\\` would not compile correctly on Unix.\n\nUsing this macro is often a bad idea, because if the file is\nparsed as an expression, it is going to be placed in the\nsurrounding code unhygienically. This could result in variables\nor functions being different from what the file expected if\nthere are variables or functions that have the same name in\nthe current file.\n\n# Examples\n\nAssume there are two files in the same directory with the following\ncontents:\n\nFile 'monkeys.in':\n\n```rust\n['🙈', '🙊', '🙉']\n .iter()\n .cycle()\n .take(6)\n .collect::<String>()\n```\n\nFile 'main.rs':\n\n```rust\nfn main() {\n let my_string = include!(\"monkeys.in\");\n assert_eq!(\"🙈🙊🙉🙈🙊🙉\", my_string);\n println!(\"{my_string}\");\n}\n```\n\nCompiling 'main.rs' and running the resulting binary will print\n\"🙈🙊🙉🙈🙊🙉\"." }, filterText = "include!", insertTextFormat = 2, kind = 3, label = "include!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "include!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! print", documentation = { kind = "markdown", value = 'Prints to the standard output.\n\nEquivalent to the [`println!`] macro except that a newline is not printed at\nthe end of the message.\n\nNote that stdout is frequently line-buffered by default so it may be\nnecessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted\nimmediately.\n\nUse `print!` only for the primary output of your program. Use\n[`eprint!`] instead to print error and progress messages.\n\n[flush]: crate::io::Write::flush\n[`println!`]: crate::println\n[`eprint!`]: crate::eprint\n\n# Panics\n\nPanics if writing to `io::stdout()` fails.\n\n# Examples\n\n```rust\nuse std::io::{self, Write};\n\nprint!("this ");\nprint!("will ");\nprint!("be ");\nprint!("on ");\nprint!("the ");\nprint!("same ");\nprint!("line ");\n\nio::stdout().flush().unwrap();\n\nprint!("this string has a newline, why not choose println! instead?\\n");\n\nio::stdout().flush().unwrap();\n```' }, filterText = "print!", insertTextFormat = 2, kind = 3, label = "print!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "print!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! concat_idents", documentation = { kind = "markdown", value = 'Concatenates identifiers into one identifier.\n\nThis macro takes any number of comma-separated identifiers, and\nconcatenates them all into one, yielding an expression which is a new\nidentifier. Note that hygiene makes it such that this macro cannot\ncapture local variables. Also, as a general rule, macros are only\nallowed in item, statement or expression position. That means while\nyou may use this macro for referring to existing variables, functions or\nmodules etc, you cannot define a new one with it.\n\n# Examples\n\n```rust\n#![feature(concat_idents)]\n\nfn foobar() -> u32 { 23 }\n\nlet f = concat_idents!(foo, bar);\nprintln!("{}", f());\n\n// fn concat_idents!(new, fun, name) { } // not usable in this way!\n```' }, filterText = "concat_idents!", insertTextFormat = 2, kind = 3, label = "concat_idents!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "concat_idents!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! write", documentation = { kind = "markdown", value = "Writes formatted data into a buffer.\n\nThis macro accepts a 'writer', a format string, and a list of arguments. Arguments will be\nformatted according to the specified format string and the result will be passed to the writer.\nThe writer may be any value with a `write_fmt` method; generally this comes from an\nimplementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro\nreturns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an\n[`io::Result`].\n\nSee [`std::fmt`] for more information on the format string syntax.\n\n[`std::fmt`]: ../std/fmt/index.html\n[`fmt::Write`]: crate::fmt::Write\n[`io::Write`]: ../std/io/trait.Write.html\n[`fmt::Result`]: crate::fmt::Result\n[`io::Result`]: ../std/io/type.Result.html\n\n# Examples\n\n```rust\nuse std::io::Write;\n\nfn main() -> std::io::Result<()> {\n let mut w = Vec::new();\n write!(&mut w, \"test\")?;\n write!(&mut w, \"formatted {}\", \"arguments\")?;\n\n assert_eq!(w, b\"testformatted arguments\");\n Ok(())\n}\n```\n\nA module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects\nimplementing either, as objects do not typically implement both. However, the module must\nimport the traits qualified so their names do not conflict:\n\n```rust\nuse std::fmt::Write as FmtWrite;\nuse std::io::Write as IoWrite;\n\nfn main() -> Result<(), Box<dyn std::error::Error>> {\n let mut s = String::new();\n let mut v = Vec::new();\n\n write!(&mut s, \"{} {}\", \"abc\", 123)?; // uses fmt::Write::write_fmt\n write!(&mut v, \"s = {:?}\", s)?; // uses io::Write::write_fmt\n assert_eq!(v, b\"s = \\\"abc 123\\\"\");\n Ok(())\n}\n```\n\nNote: This macro can be used in `no_std` setups as well.\nIn a `no_std` setup you are responsible for the implementation details of the components.\n\n```rust\nuse core::fmt::Write;\n\nstruct Example;\n\nimpl Write for Example {\n fn write_str(&mut self, _s: &str) -> core::fmt::Result {\n unimplemented!();\n }\n}\n\nlet mut m = Example{};\nwrite!(&mut m, \"Hello World\").expect(\"Not written\");\n```" }, filterText = "write!", insertTextFormat = 2, kind = 3, label = "write!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "write!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! line", documentation = { kind = "markdown", value = 'Expands to the line number on which it was invoked.\n\nWith [`column!`] and [`file!`], these macros provide debugging information for\ndevelopers about the location within the source.\n\nThe expanded expression has type `u32` and is 1-based, so the first line\nin each file evaluates to 1, the second to 2, etc. This is consistent\nwith error messages by common compilers or popular editors.\nThe returned line is *not necessarily* the line of the `line!` invocation itself,\nbut rather the first macro invocation leading up to the invocation\nof the `line!` macro.\n\n# Examples\n\n```rust\nlet current_line = line!();\nprintln!("defined on line: {current_line}");\n```' }, filterText = "line!", insertTextFormat = 2, kind = 3, label = "line!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "line!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! env", documentation = { kind = "markdown", value = "Inspects an environment variable at compile time.\n\nThis macro will expand to the value of the named environment variable at\ncompile time, yielding an expression of type `&'static str`. Use\n[`std::env::var`] instead if you want to read the value at runtime.\n\n[`std::env::var`]: ../std/env/fn.var.html\n\nIf the environment variable is not defined, then a compilation error\nwill be emitted. To not emit a compile error, use the [`option_env!`]\nmacro instead.\n\n# Examples\n\n```rust\nlet path: &'static str = env!(\"PATH\");\nprintln!(\"the $PATH variable at the time of compiling was: {path}\");\n```\n\nYou can customize the error message by passing a string as the second\nparameter:\n\n```rust\nlet doc: &'static str = env!(\"documentation\", \"what's that?!\");\n```\n\nIf the `documentation` environment variable is not defined, you'll get\nthe following error:\n\n```text\nerror: what's that?!\n```" }, filterText = "env!", insertTextFormat = 2, kind = 3, label = "env!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "env!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! debug_assert", documentation = { kind = "markdown", value = "Asserts that a boolean expression is `true` at runtime.\n\nThis will invoke the [`panic!`] macro if the provided expression cannot be\nevaluated to `true` at runtime.\n\nLike [`assert!`], this macro also has a second version, where a custom panic\nmessage can be provided.\n\n# Uses\n\nUnlike [`assert!`], `debug_assert!` statements are only enabled in non\noptimized builds by default. An optimized build will not execute\n`debug_assert!` statements unless `-C debug-assertions` is passed to the\ncompiler. This makes `debug_assert!` useful for checks that are too\nexpensive to be present in a release build but may be helpful during\ndevelopment. The result of expanding `debug_assert!` is always type checked.\n\nAn unchecked assertion allows a program in an inconsistent state to keep\nrunning, which might have unexpected consequences but does not introduce\nunsafety as long as this only happens in safe code. The performance cost\nof assertions, however, is not measurable in general. Replacing [`assert!`]\nwith `debug_assert!` is thus only encouraged after thorough profiling, and\nmore importantly, only in safe code!\n\n# Examples\n\n```rust\n// the panic message for these assertions is the stringified value of the\n// expression given.\ndebug_assert!(true);\n\nfn some_expensive_computation() -> bool { true } // a very simple function\ndebug_assert!(some_expensive_computation());\n\n// assert with a custom message\nlet x = true;\ndebug_assert!(x, \"x wasn't true!\");\n\nlet a = 3; let b = 27;\ndebug_assert!(a + b == 30, \"a = {}, b = {}\", a, b);\n```" }, filterText = "debug_assert!", insertTextFormat = 2, kind = 3, label = "debug_assert!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "debug_assert!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! const_format_args", documentation = { kind = "markdown", value = "Same as [`format_args`], but can be used in some const contexts.\n\nThis macro is used by the panic macros for the `const_panic` feature.\n\nThis macro will be removed once `format_args` is allowed in const contexts." }, filterText = "const_format_args!", insertTextFormat = 2, kind = 3, label = "const_format_args!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "const_format_args!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! include_bytes", documentation = { kind = "markdown", value = "Includes a file as a reference to a byte array.\n\nThe file is located relative to the current file (similarly to how\nmodules are found). The provided path is interpreted in a platform-specific\nway at compile time. So, for instance, an invocation with a Windows path\ncontaining backslashes `\\` would not compile correctly on Unix.\n\nThis macro will yield an expression of type `&'static [u8; N]` which is\nthe contents of the file.\n\n# Examples\n\nAssume there are two files in the same directory with the following\ncontents:\n\nFile 'spanish.in':\n\n```text\nadiós\n```\n\nFile 'main.rs':\n\n```rust\nfn main() {\n let bytes = include_bytes!(\"spanish.in\");\n assert_eq!(bytes, b\"adi\\xc3\\xb3s\\n\");\n print!(\"{}\", String::from_utf8_lossy(bytes));\n}\n```\n\nCompiling 'main.rs' and running the resulting binary will print \"adiós\"." }, filterText = "include_bytes!", insertTextFormat = 2, kind = 3, label = "include_bytes!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "include_bytes!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! thread_local", documentation = { kind = "markdown", value = "Declare a new thread local storage key of type [`std::thread::LocalKey`].\n\n# Syntax\n\nThe macro wraps any number of static declarations and makes them thread local.\nPublicity and attributes for each static are allowed. Example:\n\n```rust\nuse std::cell::RefCell;\nthread_local! {\n pub static FOO: RefCell<u32> = RefCell::new(1);\n\n #[allow(unused)]\n static BAR: RefCell<f32> = RefCell::new(1.0);\n}\n```\n\nSee [`LocalKey` documentation][`std::thread::LocalKey`] for more\ninformation.\n\n[`std::thread::LocalKey`]: crate::thread::LocalKey" }, filterText = "thread_local!", insertTextFormat = 2, kind = 3, label = "thread_local! {…}", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "thread_local! {$0}", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! file", documentation = { kind = "markdown", value = "Expands to the file name in which it was invoked.\n\nWith [`line!`] and [`column!`], these macros provide debugging information for\ndevelopers about the location within the source.\n\nThe expanded expression has type `&'static str`, and the returned file\nis not the invocation of the `file!` macro itself, but rather the\nfirst macro invocation leading up to the invocation of the `file!`\nmacro.\n\n# Examples\n\n```rust\nlet this_file = file!();\nprintln!(\"defined in file: {this_file}\");\n```" }, filterText = "file!", insertTextFormat = 2, kind = 3, label = "file!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "file!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = true, detail = "macro_rules! try", documentation = { kind = "markdown", value = 'Unwraps a result or propagates its error.\n\nThe `?` operator was added to replace `try!` and should be used instead.\nFurthermore, `try` is a reserved word in Rust 2018, so if you must use\nit, you will need to use the [raw-identifier syntax][ris]: `r#try`.\n\n[ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html\n\n`try!` matches the given [`Result`]. In case of the `Ok` variant, the\nexpression has the value of the wrapped value.\n\nIn case of the `Err` variant, it retrieves the inner error. `try!` then\nperforms conversion using `From`. This provides automatic conversion\nbetween specialized errors and more general ones. The resulting\nerror is then immediately returned.\n\nBecause of the early return, `try!` can only be used in functions that\nreturn [`Result`].\n\n# Examples\n\n```rust\nuse std::io;\nuse std::fs::File;\nuse std::io::prelude::*;\n\nenum MyError {\n FileWriteError\n}\n\nimpl From<io::Error> for MyError {\n fn from(e: io::Error) -> MyError {\n MyError::FileWriteError\n }\n}\n\n// The preferred method of quick returning Errors\nfn write_to_file_question() -> Result<(), MyError> {\n let mut file = File::create("my_best_friends.txt")?;\n file.write_all(b"This is a list of my best friends.")?;\n Ok(())\n}\n\n// The previous method of quick returning Errors\nfn write_to_file_using_try() -> Result<(), MyError> {\n let mut file = r#try!(File::create("my_best_friends.txt"));\n r#try!(file.write_all(b"This is a list of my best friends."));\n Ok(())\n}\n\n// This is equivalent to:\nfn write_to_file_using_match() -> Result<(), MyError> {\n let mut file = r#try!(File::create("my_best_friends.txt"));\n match file.write_all(b"This is a list of my best friends.") {\n Ok(v) => v,\n Err(e) => return Err(From::from(e)),\n }\n Ok(())\n}\n```' }, filterText = "try!", insertTextFormat = 2, kind = 3, label = "try!(…)", preselect = true, sortText = "ffffffef", tags = { 1 }, textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "try!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! assert", documentation = { kind = "markdown", value = "Asserts that a boolean expression is `true` at runtime.\n\nThis will invoke the [`panic!`] macro if the provided expression cannot be\nevaluated to `true` at runtime.\n\n# Uses\n\nAssertions are always checked in both debug and release builds, and cannot\nbe disabled. See [`debug_assert!`] for assertions that are not enabled in\nrelease builds by default.\n\nUnsafe code may rely on `assert!` to enforce run-time invariants that, if\nviolated could lead to unsafety.\n\nOther use-cases of `assert!` include testing and enforcing run-time\ninvariants in safe code (whose violation cannot result in unsafety).\n\n# Custom Messages\n\nThis macro has a second form, where a custom panic message can\nbe provided with or without arguments for formatting. See [`std::fmt`]\nfor syntax for this form. Expressions used as format arguments will only\nbe evaluated if the assertion fails.\n\n[`std::fmt`]: ../std/fmt/index.html\n\n# Examples\n\n```rust\n// the panic message for these assertions is the stringified value of the\n// expression given.\nassert!(true);\n\nfn some_computation() -> bool { true } // a very simple function\n\nassert!(some_computation());\n\n// assert with a custom message\nlet x = true;\nassert!(x, \"x wasn't true!\");\n\nlet a = 3; let b = 27;\nassert!(a + b == 30, \"a = {}, b = {}\", a, b);\n```" }, filterText = "assert!", insertTextFormat = 2, kind = 3, label = "assert!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "assert!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! column", documentation = { kind = "markdown", value = 'Expands to the column number at which it was invoked.\n\nWith [`line!`] and [`file!`], these macros provide debugging information for\ndevelopers about the location within the source.\n\nThe expanded expression has type `u32` and is 1-based, so the first column\nin each line evaluates to 1, the second to 2, etc. This is consistent\nwith error messages by common compilers or popular editors.\nThe returned column is *not necessarily* the line of the `column!` invocation itself,\nbut rather the first macro invocation leading up to the invocation\nof the `column!` macro.\n\n# Examples\n\n```rust\nlet current_col = column!();\nprintln!("defined on column: {current_col}");\n```\n\n`column!` counts Unicode code points, not bytes or graphemes. As a result, the first two\ninvocations return the same value, but the third does not.\n\n```rust\nlet a = ("foobar", column!()).1;\nlet b = ("人之初性本善", column!()).1;\nlet c = ("f̅o̅o̅b̅a̅r̅", column!()).1; // Uses combining overline (U+0305)\n\nassert_eq!(a, b);\nassert_ne!(b, c);\n```' }, filterText = "column!", insertTextFormat = 2, kind = 3, label = "column!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "column!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! format_args_nl", documentation = { kind = "markdown", value = "Same as [`format_args`], but adds a newline in the end." }, filterText = "format_args_nl!", insertTextFormat = 2, kind = 3, label = "format_args_nl!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "format_args_nl!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! unreachable", documentation = { kind = "markdown", value = "Indicates unreachable code.\n\nThis is useful any time that the compiler can't determine that some code is unreachable. For\nexample:\n\n* Match arms with guard conditions.\n* Loops that dynamically terminate.\n* Iterators that dynamically terminate.\n\nIf the determination that the code is unreachable proves incorrect, the\nprogram immediately terminates with a [`panic!`].\n\nThe unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which\nwill cause undefined behavior if the code is reached.\n\n[`unreachable_unchecked`]: crate::hint::unreachable_unchecked\n\n# Panics\n\nThis will always [`panic!`] because `unreachable!` is just a shorthand for `panic!` with a\nfixed, specific message.\n\nLike `panic!`, this macro has a second form for displaying custom values.\n\n# Examples\n\nMatch arms:\n\n```rust\nfn foo(x: Option<i32>) {\n match x {\n Some(n) if n >= 0 => println!(\"Some(Non-negative)\"),\n Some(n) if n < 0 => println!(\"Some(Negative)\"),\n Some(_) => unreachable!(), // compile error if commented out\n None => println!(\"None\")\n }\n}\n```\n\nIterators:\n\n```rust\nfn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3\n for i in 0.. {\n if 3*i < i { panic!(\"u32 overflow\"); }\n if x < 3*i { return i-1; }\n }\n unreachable!(\"The loop should always return\");\n}\n```" }, filterText = "unreachable!", insertTextFormat = 2, kind = 3, label = "unreachable!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "unreachable!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! eprintln", documentation = { kind = "markdown", value = 'Prints to the standard error, with a newline.\n\nEquivalent to the [`println!`] macro, except that output goes to\n[`io::stderr`] instead of [`io::stdout`]. See [`println!`] for\nexample usage.\n\nUse `eprintln!` only for error and progress messages. Use `println!`\ninstead for the primary output of your program.\n\n[`io::stderr`]: crate::io::stderr\n[`io::stdout`]: crate::io::stdout\n[`println!`]: crate::println\n\n# Panics\n\nPanics if writing to `io::stderr` fails.\n\n# Examples\n\n```rust\neprintln!("Error: Could not complete task");\n```' }, filterText = "eprintln!", insertTextFormat = 2, kind = 3, label = "eprintln!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "eprintln!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! unimplemented", documentation = { kind = "markdown", value = "Indicates unimplemented code by panicking with a message of \"not implemented\".\n\nThis allows your code to type-check, which is useful if you are prototyping or\nimplementing a trait that requires multiple methods which you don't plan to use all of.\n\nThe difference between `unimplemented!` and [`todo!`] is that while `todo!`\nconveys an intent of implementing the functionality later and the message is \"not yet\nimplemented\", `unimplemented!` makes no such claims. Its message is \"not implemented\".\nAlso some IDEs will mark `todo!`s.\n\n# Panics\n\nThis will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a\nfixed, specific message.\n\nLike `panic!`, this macro has a second form for displaying custom values.\n\n[`todo!`]: crate::todo\n\n# Examples\n\nSay we have a trait `Foo`:\n\n```rust\ntrait Foo {\n fn bar(&self) -> u8;\n fn baz(&self);\n fn qux(&self) -> Result<u64, ()>;\n}\n```\n\nWe want to implement `Foo` for 'MyStruct', but for some reason it only makes sense\nto implement the `bar()` function. `baz()` and `qux()` will still need to be defined\nin our implementation of `Foo`, but we can use `unimplemented!` in their definitions\nto allow our code to compile.\n\nWe still want to have our program stop running if the unimplemented methods are\nreached.\n\n```rust\nstruct MyStruct;\n\nimpl Foo for MyStruct {\n fn bar(&self) -> u8 {\n 1 + 1\n }\n\n fn baz(&self) {\n // It makes no sense to `baz` a `MyStruct`, so we have no logic here\n // at all.\n // This will display \"thread 'main' panicked at 'not implemented'\".\n unimplemented!();\n }\n\n fn qux(&self) -> Result<u64, ()> {\n // We have some logic here,\n // We can add a message to unimplemented! to display our omission.\n // This will display:\n // \"thread 'main' panicked at 'not implemented: MyStruct isn't quxable'\".\n unimplemented!(\"MyStruct isn't quxable\");\n }\n}\n\nfn main() {\n let s = MyStruct;\n s.bar();\n}\n```" }, filterText = "unimplemented!", insertTextFormat = 2, kind = 3, label = "unimplemented!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "unimplemented!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! cfg", documentation = { kind = "markdown", value = 'Evaluates boolean combinations of configuration flags at compile-time.\n\nIn addition to the `#[cfg]` attribute, this macro is provided to allow\nboolean expression evaluation of configuration flags. This frequently\nleads to less duplicated code.\n\nThe syntax given to this macro is the same syntax as the [`cfg`]\nattribute.\n\n`cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For\nexample, all blocks in an if/else expression need to be valid when `cfg!` is used for\nthe condition, regardless of what `cfg!` is evaluating.\n\n[`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute\n\n# Examples\n\n```rust\nlet my_directory = if cfg!(windows) {\n "windows-specific-directory"\n} else {\n "unix-directory"\n};\n```' }, filterText = "cfg!", insertTextFormat = 2, kind = 3, label = "cfg!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "cfg!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! todo", documentation = { kind = "markdown", value = "Indicates unfinished code.\n\nThis can be useful if you are prototyping and are just looking to have your\ncode typecheck.\n\nThe difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys\nan intent of implementing the functionality later and the message is \"not yet\nimplemented\", `unimplemented!` makes no such claims. Its message is \"not implemented\".\nAlso some IDEs will mark `todo!`s.\n\n# Panics\n\nThis will always [`panic!`].\n\n# Examples\n\nHere's an example of some in-progress code. We have a trait `Foo`:\n\n```rust\ntrait Foo {\n fn bar(&self);\n fn baz(&self);\n}\n```\n\nWe want to implement `Foo` on one of our types, but we also want to work on\njust `bar()` first. In order for our code to compile, we need to implement\n`baz()`, so we can use `todo!`:\n\n```rust\nstruct MyStruct;\n\nimpl Foo for MyStruct {\n fn bar(&self) {\n // implementation goes here\n }\n\n fn baz(&self) {\n // let's not worry about implementing baz() for now\n todo!();\n }\n}\n\nfn main() {\n let s = MyStruct;\n s.bar();\n\n // we aren't even using baz(), so this is fine.\n}\n```" }, filterText = "todo!", insertTextFormat = 2, kind = 3, label = "todo!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "todo!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! trace_macros", documentation = { kind = "markdown", value = "Enables or disables tracing functionality used for debugging other macros." }, filterText = "trace_macros!", insertTextFormat = 2, kind = 3, label = "trace_macros!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "trace_macros!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! module_path", documentation = { kind = "markdown", value = 'Expands to a string that represents the current module path.\n\nThe current module path can be thought of as the hierarchy of modules\nleading back up to the crate root. The first component of the path\nreturned is the name of the crate currently being compiled.\n\n# Examples\n\n```rust\nmod test {\n pub fn foo() {\n assert!(module_path!().ends_with("test"));\n }\n}\n\ntest::foo();\n```' }, filterText = "module_path!", insertTextFormat = 2, kind = 3, label = "module_path!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "module_path!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! writeln", documentation = { kind = "markdown", value = 'Write formatted data into a buffer, with a newline appended.\n\nOn all platforms, the newline is the LINE FEED character (`\\n`/`U+000A`) alone\n(no additional CARRIAGE RETURN (`\\r`/`U+000D`).\n\nFor more information, see [`write!`]. For information on the format string syntax, see\n[`std::fmt`].\n\n[`std::fmt`]: ../std/fmt/index.html\n\n# Examples\n\n```rust\nuse std::io::{Write, Result};\n\nfn main() -> Result<()> {\n let mut w = Vec::new();\n writeln!(&mut w)?;\n writeln!(&mut w, "test")?;\n writeln!(&mut w, "formatted {}", "arguments")?;\n\n assert_eq!(&w[..], "\\ntest\\nformatted arguments\\n".as_bytes());\n Ok(())\n}\n```\n\nA module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects\nimplementing either, as objects do not typically implement both. However, the module must\nimport the traits qualified so their names do not conflict:\n\n```rust\nuse std::fmt::Write as FmtWrite;\nuse std::io::Write as IoWrite;\n\nfn main() -> Result<(), Box<dyn std::error::Error>> {\n let mut s = String::new();\n let mut v = Vec::new();\n\n writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt\n writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt\n assert_eq!(v, b"s = \\"abc 123\\\\n\\"\\n");\n Ok(())\n}\n```' }, filterText = "writeln!", insertTextFormat = 2, kind = 3, label = "writeln!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "writeln!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! option_env", documentation = { kind = "markdown", value = "Optionally inspects an environment variable at compile time.\n\nIf the named environment variable is present at compile time, this will\nexpand into an expression of type `Option<&'static str>` whose value is\n`Some` of the value of the environment variable. If the environment\nvariable is not present, then this will expand to `None`. See\n[`Option<T>`][Option] for more information on this type. Use\n[`std::env::var`] instead if you want to read the value at runtime.\n\n[`std::env::var`]: ../std/env/fn.var.html\n\nA compile time error is never emitted when using this macro regardless\nof whether the environment variable is present or not.\n\n# Examples\n\n```rust\nlet key: Option<&'static str> = option_env!(\"SECRET_KEY\");\nprintln!(\"the secret key might be: {key:?}\");\n```" }, filterText = "option_env!", insertTextFormat = 2, kind = 3, label = "option_env!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "option_env!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! compile_error", documentation = { kind = "markdown", value = "Causes compilation to fail with the given error message when encountered.\n\nThis macro should be used when a crate uses a conditional compilation strategy to provide\nbetter error messages for erroneous conditions. It's the compiler-level form of [`panic!`],\nbut emits an error during *compilation* rather than at *runtime*.\n\n# Examples\n\nTwo such examples are macros and `#[cfg]` environments.\n\nEmit better compiler error if a macro is passed invalid values. Without the final branch,\nthe compiler would still emit an error, but the error's message would not mention the two\nvalid values.\n\n```rust\nmacro_rules! give_me_foo_or_bar {\n (foo) => {};\n (bar) => {};\n ($x:ident) => {\n compile_error!(\"This macro only accepts `foo` or `bar`\");\n }\n}\n\ngive_me_foo_or_bar!(neither);\n// ^ will fail at compile time with message \"This macro only accepts `foo` or `bar`\"\n```\n\nEmit compiler error if one of a number of features isn't available.\n\n```rust\n#[cfg(not(any(feature = \"foo\", feature = \"bar\")))]\ncompile_error!(\"Either feature \\\"foo\\\" or \\\"bar\\\" must be enabled for this crate.\");\n```" }, filterText = "compile_error!", insertTextFormat = 2, kind = 3, label = "compile_error!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "compile_error!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! matches", documentation = { kind = "markdown", value = "Returns whether the given expression matches any of the given patterns.\n\nLike in a `match` expression, the pattern can be optionally followed by `if`\nand a guard expression that has access to names bound by the pattern.\n\n# Examples\n\n```rust\nlet foo = 'f';\nassert!(matches!(foo, 'A'..='Z' | 'a'..='z'));\n\nlet bar = Some(4);\nassert!(matches!(bar, Some(x) if x > 2));\n```" }, filterText = "matches!", insertTextFormat = 2, kind = 3, label = "matches!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "matches!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! println", documentation = { kind = "markdown", value = 'Prints to the standard output, with a newline.\n\nOn all platforms, the newline is the LINE FEED character (`\\n`/`U+000A`) alone\n(no additional CARRIAGE RETURN (`\\r`/`U+000D`)).\n\nUse the [`format!`] syntax to write data to the standard output.\nSee [`std::fmt`] for more information.\n\nUse `println!` only for the primary output of your program. Use\n[`eprintln!`] instead to print error and progress messages.\n\n[`std::fmt`]: crate::fmt\n[`eprintln!`]: crate::eprintln\n\n# Panics\n\nPanics if writing to [`io::stdout`] fails.\n\n[`io::stdout`]: crate::io::stdout\n\n# Examples\n\n```rust\nprintln!(); // prints just a newline\nprintln!("hello there!");\nprintln!("format {} arguments", "some");\n```' }, filterText = "println!", insertTextFormat = 2, kind = 3, label = "println!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "println!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! concat_bytes", documentation = { kind = "markdown", value = "Concatenates literals into a byte slice.\n\nThis macro takes any number of comma-separated literals, and concatenates them all into\none, yielding an expression of type `&[u8, _]`, which represents all of the literals\nconcatenated left-to-right. The literals passed can be any combination of:\n\n- byte literals (`b'r'`)\n- byte strings (`b\"Rust\"`)\n- arrays of bytes/numbers (`[b'A', 66, b'C']`)\n\n# Examples\n\n```rust\n#![feature(concat_bytes)]\n\nlet s: &[u8; 6] = concat_bytes!(b'A', b\"BC\", [68, b'E', 70]);\nassert_eq!(s, b\"ABCDEF\");\n```" }, filterText = "concat_bytes!", insertTextFormat = 2, kind = 3, label = "concat_bytes!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "concat_bytes!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! assert_eq", documentation = { kind = "markdown", value = 'Asserts that two expressions are equal to each other (using [`PartialEq`]).\n\nOn panic, this macro will print the values of the expressions with their\ndebug representations.\n\nLike [`assert!`], this macro has a second form, where a custom\npanic message can be provided.\n\n# Examples\n\n```rust\nlet a = 3;\nlet b = 1 + 2;\nassert_eq!(a, b);\n\nassert_eq!(a, b, "we are testing addition with {} and {}", a, b);\n```' }, filterText = "assert_eq!", insertTextFormat = 2, kind = 3, label = "assert_eq!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "assert_eq!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! is_x86_feature_detected", documentation = { kind = "markdown", value = 'A macro to test at *runtime* whether a CPU feature is available on\nx86/x86-64 platforms.\n\nThis macro is provided in the standard library and will detect at runtime\nwhether the specified CPU feature is detected. This does **not** resolve at\ncompile time unless the specified feature is already enabled for the entire\ncrate. Runtime detection currently relies mostly on the `cpuid` instruction.\n\nThis macro only takes one argument which is a string literal of the feature\nbeing tested for. The feature names supported are the lowercase versions of\nthe ones defined by Intel in [their documentation][docs].\n\n## Supported arguments\n\nThis macro supports the same names that `#[target_feature]` supports. Unlike\n`#[target_feature]`, however, this macro does not support names separated\nwith a comma. Instead testing for multiple features must be done through\nseparate macro invocations for now.\n\nSupported arguments are:\n\n* `"aes"`\n* `"pclmulqdq"`\n* `"rdrand"`\n* `"rdseed"`\n* `"tsc"`\n* `"mmx"`\n* `"sse"`\n* `"sse2"`\n* `"sse3"`\n* `"ssse3"`\n* `"sse4.1"`\n* `"sse4.2"`\n* `"sse4a"`\n* `"sha"`\n* `"avx"`\n* `"avx2"`\n* `"avx512f"`\n* `"avx512cd"`\n* `"avx512er"`\n* `"avx512pf"`\n* `"avx512bw"`\n* `"avx512dq"`\n* `"avx512vl"`\n* `"avx512ifma"`\n* `"avx512vbmi"`\n* `"avx512vpopcntdq"`\n* `"avx512vbmi2"`\n* `"avx512gfni"`\n* `"avx512vaes"`\n* `"avx512vpclmulqdq"`\n* `"avx512vnni"`\n* `"avx512bitalg"`\n* `"avx512bf16"`\n* `"avx512vp2intersect"`\n* `"f16c"`\n* `"fma"`\n* `"bmi1"`\n* `"bmi2"`\n* `"abm"`\n* `"lzcnt"`\n* `"tbm"`\n* `"popcnt"`\n* `"fxsr"`\n* `"xsave"`\n* `"xsaveopt"`\n* `"xsaves"`\n* `"xsavec"`\n* `"cmpxchg16b"`\n* `"adx"`\n* `"rtm"`\n\n[docs]: https://software.intel.com/sites/landingpage/IntrinsicsGuide' }, filterText = "is_x86_feature_detected!", insertTextFormat = 2, kind = 3, label = "is_x86_feature_detected!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "is_x86_feature_detected!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! format_args", documentation = { kind = "markdown", value = 'Constructs parameters for the other string-formatting macros.\n\nThis macro functions by taking a formatting string literal containing\n`{}` for each additional argument passed. `format_args!` prepares the\nadditional parameters to ensure the output can be interpreted as a string\nand canonicalizes the arguments into a single type. Any value that implements\nthe [`Display`] trait can be passed to `format_args!`, as can any\n[`Debug`] implementation be passed to a `{:?}` within the formatting string.\n\nThis macro produces a value of type [`fmt::Arguments`]. This value can be\npassed to the macros within [`std::fmt`] for performing useful redirection.\nAll other formatting macros ([`format!`], [`write!`], [`println!`], etc) are\nproxied through this one. `format_args!`, unlike its derived macros, avoids\nheap allocations.\n\nYou can use the [`fmt::Arguments`] value that `format_args!` returns\nin `Debug` and `Display` contexts as seen below. The example also shows\nthat `Debug` and `Display` format to the same thing: the interpolated\nformat string in `format_args!`.\n\n```rust\nlet debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));\nlet display = format!("{}", format_args!("{} foo {:?}", 1, 2));\nassert_eq!("1 foo 2", display);\nassert_eq!(display, debug);\n```\n\nFor more information, see the documentation in [`std::fmt`].\n\n[`Display`]: crate::fmt::Display\n[`Debug`]: crate::fmt::Debug\n[`fmt::Arguments`]: crate::fmt::Arguments\n[`std::fmt`]: ../std/fmt/index.html\n[`format!`]: ../std/macro.format.html\n[`println!`]: ../std/macro.println.html\n\n# Examples\n\n```rust\nuse std::fmt;\n\nlet s = fmt::format(format_args!("hello {}", "world"));\nassert_eq!(s, format!("hello {}", "world"));\n```' }, filterText = "format_args!", insertTextFormat = 2, kind = 3, label = "format_args!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "format_args!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, detail = "macro_rules! debug_assert_ne", documentation = { kind = "markdown", value = "Asserts that two expressions are not equal to each other.\n\nOn panic, this macro will print the values of the expressions with their\ndebug representations.\n\nUnlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non\noptimized builds by default. An optimized build will not execute\n`debug_assert_ne!` statements unless `-C debug-assertions` is passed to the\ncompiler. This makes `debug_assert_ne!` useful for checks that are too\nexpensive to be present in a release build but may be helpful during\ndevelopment. The result of expanding `debug_assert_ne!` is always type checked.\n\n# Examples\n\n```rust\nlet a = 3;\nlet b = 2;\ndebug_assert_ne!(a, b);\n```" }, filterText = "debug_assert_ne!", insertTextFormat = 2, kind = 3, label = "debug_assert_ne!(…)", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "debug_assert_ne!($0)", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "# The Rust Standard Library\n\nThe Rust Standard Library is the foundation of portable Rust software, a\nset of minimal and battle-tested shared abstractions for the [broader Rust\necosystem][crates.io]. It offers core types, like [`Vec<T>`] and\n[`Option<T>`], library-defined [operations on language\nprimitives](#primitives), [standard macros](#macros), [I/O] and\n[multithreading], among [many other things][other].\n\n`std` is available to all Rust crates by default. Therefore, the\nstandard library can be accessed in [`use`] statements through the path\n`std`, as in [`use std::env`].\n\n# How to read this documentation\n\nIf you already know the name of what you are looking for, the fastest way to\nfind it is to use the <a href=\"#\" onclick=\"focusSearchBar();\">search\nbar</a> at the top of the page.\n\nOtherwise, you may want to jump to one of these useful sections:\n\n* [`std::*` modules](#modules)\n* [Primitive types](#primitives)\n* [Standard macros](#macros)\n* [The Rust Prelude]\n\nIf this is your first time, the documentation for the standard library is\nwritten to be casually perused. Clicking on interesting things should\ngenerally lead you to interesting places. Still, there are important bits\nyou don't want to miss, so read on for a tour of the standard library and\nits documentation!\n\nOnce you are familiar with the contents of the standard library you may\nbegin to find the verbosity of the prose distracting. At this stage in your\ndevelopment you may want to press the `[-]` button near the top of the\npage to collapse it into a more skimmable view.\n\nWhile you are looking at that `[-]` button also notice the `source`\nlink. Rust's API documentation comes with the source code and you are\nencouraged to read it. The standard library source is generally high\nquality and a peek behind the curtains is often enlightening.\n\n# What is in the standard library documentation?\n\nFirst of all, The Rust Standard Library is divided into a number of focused\nmodules, [all listed further down this page](#modules). These modules are\nthe bedrock upon which all of Rust is forged, and they have mighty names\nlike [`std::slice`] and [`std::cmp`]. Modules' documentation typically\nincludes an overview of the module along with examples, and are a smart\nplace to start familiarizing yourself with the library.\n\nSecond, implicit methods on [primitive types] are documented here. This can\nbe a source of confusion for two reasons:\n\n1. While primitives are implemented by the compiler, the standard library\n implements methods directly on the primitive types (and it is the only\n library that does so), which are [documented in the section on\n primitives](#primitives).\n2. The standard library exports many modules *with the same name as\n primitive types*. These define additional items related to the primitive\n type, but not the all-important methods.\n\nSo for example there is a [page for the primitive type\n`i32`](primitive::i32) that lists all the methods that can be called on\n32-bit integers (very useful), and there is a [page for the module\n`std::i32`] that documents the constant values [`MIN`] and [`MAX`] (rarely\nuseful).\n\nNote the documentation for the primitives [`str`] and [`[T]`][prim@slice] (also\ncalled 'slice'). Many method calls on [`String`] and [`Vec<T>`] are actually\ncalls to methods on [`str`] and [`[T]`][prim@slice] respectively, via [deref\ncoercions][deref-coercions].\n\nThird, the standard library defines [The Rust Prelude], a small collection\nof items - mostly traits - that are imported into every module of every\ncrate. The traits in the prelude are pervasive, making the prelude\ndocumentation a good entry point to learning about the library.\n\nAnd finally, the standard library exports a number of standard macros, and\n[lists them on this page](#macros) (technically, not all of the standard\nmacros are defined by the standard library - some are defined by the\ncompiler - but they are documented here the same). Like the prelude, the\nstandard macros are imported by default into all crates.\n\n# Contributing changes to the documentation\n\nCheck out the rust contribution guidelines [here](\nhttps://rustc-dev-guide.rust-lang.org/contributing.html#writing-documentation).\nThe source for this documentation can be found on\n[GitHub](https://github.com/rust-lang/rust).\nTo contribute changes, make sure you read the guidelines first, then submit\npull-requests for your suggested changes.\n\nContributions are appreciated! If you see a part of the docs that can be\nimproved, submit a PR, or chat with us first on [Discord][rust-discord]\n#docs.\n\n# A Tour of The Rust Standard Library\n\nThe rest of this crate documentation is dedicated to pointing out notable\nfeatures of The Rust Standard Library.\n\n## Containers and collections\n\nThe [`option`] and [`result`] modules define optional and error-handling\ntypes, [`Option<T>`] and [`Result<T, E>`]. The [`iter`] module defines\nRust's iterator trait, [`Iterator`], which works with the [`for`] loop to\naccess collections.\n\nThe standard library exposes three common ways to deal with contiguous\nregions of memory:\n\n* [`Vec<T>`] - A heap-allocated *vector* that is resizable at runtime.\n* [`[T; N]`][prim@array] - An inline *array* with a fixed size at compile time.\n* [`[T]`][prim@slice] - A dynamically sized *slice* into any other kind of contiguous\n storage, whether heap-allocated or not.\n\nSlices can only be handled through some kind of *pointer*, and as such come\nin many flavors such as:\n\n* `&[T]` - *shared slice*\n* `&mut [T]` - *mutable slice*\n* [`Box<[T]>`][owned slice] - *owned slice*\n\n[`str`], a UTF-8 string slice, is a primitive type, and the standard library\ndefines many methods for it. Rust [`str`]s are typically accessed as\nimmutable references: `&str`. Use the owned [`String`] for building and\nmutating strings.\n\nFor converting to strings use the [`format!`] macro, and for converting from\nstrings use the [`FromStr`] trait.\n\nData may be shared by placing it in a reference-counted box or the [`Rc`]\ntype, and if further contained in a [`Cell`] or [`RefCell`], may be mutated\nas well as shared. Likewise, in a concurrent setting it is common to pair an\natomically-reference-counted box, [`Arc`], with a [`Mutex`] to get the same\neffect.\n\nThe [`collections`] module defines maps, sets, linked lists and other\ntypical collection types, including the common [`HashMap<K, V>`].\n\n## Platform abstractions and I/O\n\nBesides basic data types, the standard library is largely concerned with\nabstracting over differences in common platforms, most notably Windows and\nUnix derivatives.\n\nCommon types of I/O, including [files], [TCP], [UDP], are defined in the\n[`io`], [`fs`], and [`net`] modules.\n\nThe [`thread`] module contains Rust's threading abstractions. [`sync`]\ncontains further primitive shared memory types, including [`atomic`] and\n[`mpsc`], which contains the channel types for message passing.\n\n[I/O]: io\n[`MIN`]: i32::MIN\n[`MAX`]: i32::MAX\n[page for the module `std::i32`]: crate::i32\n[TCP]: net::TcpStream\n[The Rust Prelude]: prelude\n[UDP]: net::UdpSocket\n[`Arc`]: sync::Arc\n[owned slice]: boxed\n[`Cell`]: cell::Cell\n[`FromStr`]: str::FromStr\n[`HashMap<K, V>`]: collections::HashMap\n[`Mutex`]: sync::Mutex\n[`Option<T>`]: option::Option\n[`Rc`]: rc::Rc\n[`RefCell`]: cell::RefCell\n[`Result<T, E>`]: result::Result\n[`Vec<T>`]: vec::Vec\n[`atomic`]: sync::atomic\n[`for`]: ../book/ch03-05-control-flow.html#looping-through-a-collection-with-for\n[`str`]: prim@str\n[`mpsc`]: sync::mpsc\n[`std::cmp`]: cmp\n[`std::slice`]: mod@slice\n[`use std::env`]: env/index.html\n[`use`]: ../book/ch07-02-defining-modules-to-control-scope-and-privacy.html\n[crates.io]: https://crates.io\n[deref-coercions]: ../book/ch15-02-deref.html#implicit-deref-coercions-with-functions-and-methods\n[files]: fs::File\n[multithreading]: thread\n[other]: #what-is-in-the-standard-library-documentation\n[primitive types]: ../book/ch03-02-data-types.html\n[rust-discord]: https://discord.gg/rust-lang\n[array]: prim@array\n[slice]: prim@slice" }, filterText = "std", kind = 9, label = "std", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "std", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "[![github]](https://github.com/dtolnay/proc-macro2)&ensp;[![crates-io]](https://crates.io/crates/proc-macro2)&ensp;[![docs-rs]](crate)\n\n[github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github\n[crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust\n[docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K\n\n<br>\n\nA wrapper around the procedural macro API of the compiler's [`proc_macro`]\ncrate. This library serves two purposes:\n\n[`proc_macro`]: https://doc.rust-lang.org/proc_macro/\n\n- **Bring proc-macro-like functionality to other contexts like build.rs and\n main.rs.** Types from `proc_macro` are entirely specific to procedural\n macros and cannot ever exist in code outside of a procedural macro.\n Meanwhile `proc_macro2` types may exist anywhere including non-macro code.\n By developing foundational libraries like [syn] and [quote] against\n `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem\n becomes easily applicable to many other use cases and we avoid\n reimplementing non-macro equivalents of those libraries.\n\n- **Make procedural macros unit testable.** As a consequence of being\n specific to procedural macros, nothing that uses `proc_macro` can be\n executed from a unit test. In order for helper libraries or components of\n a macro to be testable in isolation, they must be implemented using\n `proc_macro2`.\n\n[syn]: https://github.com/dtolnay/syn\n[quote]: https://github.com/dtolnay/quote\n\n# Usage\n\nThe skeleton of a typical procedural macro typically looks like this:\n\n```rust\nextern crate proc_macro;\n\n#[proc_macro_derive(MyDerive)]\npub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n let input = proc_macro2::TokenStream::from(input);\n\n let output: proc_macro2::TokenStream = {\n /* transform input */\n };\n\n proc_macro::TokenStream::from(output)\n}\n```\n\nIf parsing with [Syn], you'll use [`parse_macro_input!`] instead to\npropagate parse errors correctly back to the compiler when parsing fails.\n\n[`parse_macro_input!`]: https://docs.rs/syn/1.0/syn/macro.parse_macro_input.html\n\n# Unstable features\n\nThe default feature set of proc-macro2 tracks the most recent stable\ncompiler API. Functionality in `proc_macro` that is not yet stable is not\nexposed by proc-macro2 by default.\n\nTo opt into the additional APIs available in the most recent nightly\ncompiler, the `procmacro2_semver_exempt` config flag must be passed to\nrustc. We will polyfill those nightly-only APIs back to Rust 1.31.0. As\nthese are unstable APIs that track the nightly compiler, minor versions of\nproc-macro2 may make breaking changes to them at any time.\n\n```sh\nRUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build\n```\n\nNote that this must not only be done for your crate, but for any crate that\ndepends on your crate. This infectious nature is intentional, as it serves\nas a reminder that you are outside of the normal semver guarantees.\n\nSemver exempt methods are marked as such in the proc-macro2 documentation.\n\n# Thread-Safety\n\nMost types in this crate are `!Sync` because the underlying compiler\ntypes make use of thread-local memory, meaning they cannot be accessed from\na different thread." }, filterText = "proc_macro2", kind = 9, label = "proc_macro2", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "proc_macro2", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "vyhex", kind = 9, label = "vyhex", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "vyhex", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "# The Rust core allocation and collections library\n\nThis library provides smart pointers and collections for managing\nheap-allocated values.\n\nThis library, like libcore, normally doesn’t need to be used directly\nsince its contents are re-exported in the [`std` crate](../std/index.html).\nCrates that use the `#![no_std]` attribute however will typically\nnot depend on `std`, so they’d use this crate instead.\n\n## Boxed values\n\nThe [`Box`] type is a smart pointer type. There can only be one owner of a\n[`Box`], and the owner can decide to mutate the contents, which live on the\nheap.\n\nThis type can be sent among threads efficiently as the size of a `Box` value\nis the same as that of a pointer. Tree-like data structures are often built\nwith boxes because each node often has only one owner, the parent.\n\n## Reference counted pointers\n\nThe [`Rc`] type is a non-threadsafe reference-counted pointer type intended\nfor sharing memory within a thread. An [`Rc`] pointer wraps a type, `T`, and\nonly allows access to `&T`, a shared reference.\n\nThis type is useful when inherited mutability (such as using [`Box`]) is too\nconstraining for an application, and is often paired with the [`Cell`] or\n[`RefCell`] types in order to allow mutation.\n\n## Atomically reference counted pointers\n\nThe [`Arc`] type is the threadsafe equivalent of the [`Rc`] type. It\nprovides all the same functionality of [`Rc`], except it requires that the\ncontained type `T` is shareable. Additionally, [`Arc<T>`][`Arc`] is itself\nsendable while [`Rc<T>`][`Rc`] is not.\n\nThis type allows for shared access to the contained data, and is often\npaired with synchronization primitives such as mutexes to allow mutation of\nshared resources.\n\n## Collections\n\nImplementations of the most common general purpose data structures are\ndefined in this library. They are re-exported through the\n[standard collections library](../std/collections/index.html).\n\n## Heap interfaces\n\nThe [`alloc`](alloc/index.html) module defines the low-level interface to the\ndefault global allocator. It is not compatible with the libc allocator API.\n\n[`Arc`]: sync\n[`Box`]: boxed\n[`Cell`]: core::cell\n[`Rc`]: rc\n[`RefCell`]: core::cell" }, filterText = "alloc", kind = 9, label = "alloc", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "alloc", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "# The Rust Core Library\n\nThe Rust Core Library is the dependency-free[^free] foundation of [The\nRust Standard Library](../std/index.html). It is the portable glue\nbetween the language and its libraries, defining the intrinsic and\nprimitive building blocks of all Rust code. It links to no\nupstream libraries, no system libraries, and no libc.\n\n[^free]: Strictly speaking, there are some symbols which are needed but\n they aren't always necessary.\n\nThe core library is *minimal*: it isn't even aware of heap allocation,\nnor does it provide concurrency or I/O. These things require\nplatform integration, and this library is platform-agnostic.\n\n# How to use the core library\n\nPlease note that all of these details are currently not considered stable.\n\nThis library is built on the assumption of a few existing symbols:\n\n* `memcpy`, `memcmp`, `memset`, `strlen` - These are core memory routines which are\n often generated by LLVM. Additionally, this library can make explicit\n calls to these functions. Their signatures are the same as found in C.\n These functions are often provided by the system libc, but can also be\n provided by the [compiler-builtins crate](https://crates.io/crates/compiler_builtins).\n\n* `rust_begin_panic` - This function takes four arguments, a\n `fmt::Arguments`, a `&'static str`, and two `u32`'s. These four arguments\n dictate the panic message, the file at which panic was invoked, and the\n line and column inside the file. It is up to consumers of this core\n library to define this panic function; it is only required to never\n return. This requires a `lang` attribute named `panic_impl`.\n\n* `rust_eh_personality` - is used by the failure mechanisms of the\n compiler. This is often mapped to GCC's personality function, but crates\n which do not trigger a panic can be assured that this function is never\n called. The `lang` attribute is called `eh_personality`." }, filterText = "core", kind = 9, label = "core", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "core", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "A runtime for writing reliable network applications without compromising speed.\n\nTokio is an event-driven, non-blocking I/O platform for writing asynchronous\napplications with the Rust programming language. At a high level, it\nprovides a few major components:\n\n* Tools for [working with asynchronous tasks][tasks], including\n [synchronization primitives and channels][sync] and [timeouts, sleeps, and\n intervals][time].\n* APIs for [performing asynchronous I/O][io], including [TCP and UDP][net] sockets,\n [filesystem][fs] operations, and [process] and [signal] management.\n* A [runtime] for executing asynchronous code, including a task scheduler,\n an I/O driver backed by the operating system's event queue (epoll, kqueue,\n IOCP, etc...), and a high performance timer.\n\nGuide level documentation is found on the [website].\n\n[tasks]: #working-with-tasks\n[sync]: crate::sync\n[time]: crate::time\n[io]: #asynchronous-io\n[net]: crate::net\n[fs]: crate::fs\n[process]: crate::process\n[signal]: crate::signal\n[fs]: crate::fs\n[runtime]: crate::runtime\n[website]: https://tokio.rs/tokio/tutorial\n\n# A Tour of Tokio\n\nTokio consists of a number of modules that provide a range of functionality\nessential for implementing asynchronous applications in Rust. In this\nsection, we will take a brief tour of Tokio, summarizing the major APIs and\ntheir uses.\n\nThe easiest way to get started is to enable all features. Do this by\nenabling the `full` feature flag:\n\n```toml\ntokio = { version = \"1\", features = [\"full\"] }\n```\n\n### Authoring applications\n\nTokio is great for writing applications and most users in this case shouldn't\nworry too much about what features they should pick. If you're unsure, we suggest\ngoing with `full` to ensure that you don't run into any road blocks while you're\nbuilding your application.\n\n#### Example\n\nThis example shows the quickest way to get started with Tokio.\n\n```toml\ntokio = { version = \"1\", features = [\"full\"] }\n```\n\n### Authoring libraries\n\nAs a library author your goal should be to provide the lightest weight crate\nthat is based on Tokio. To achieve this you should ensure that you only enable\nthe features you need. This allows users to pick up your crate without having\nto enable unnecessary features.\n\n#### Example\n\nThis example shows how you may want to import features for a library that just\nneeds to `tokio::spawn` and use a `TcpStream`.\n\n```toml\ntokio = { version = \"1\", features = [\"rt\", \"net\"] }\n```\n\n## Working With Tasks\n\nAsynchronous programs in Rust are based around lightweight, non-blocking\nunits of execution called [_tasks_][tasks]. The [`tokio::task`] module provides\nimportant tools for working with tasks:\n\n* The [`spawn`] function and [`JoinHandle`] type, for scheduling a new task\n on the Tokio runtime and awaiting the output of a spawned task, respectively,\n* Functions for [running blocking operations][blocking] in an asynchronous\n task context.\n\nThe [`tokio::task`] module is present only when the \"rt\" feature flag\nis enabled.\n\n[tasks]: task/index.html#what-are-tasks\n[`tokio::task`]: crate::task\n[`spawn`]: crate::task::spawn()\n[`JoinHandle`]: crate::task::JoinHandle\n[blocking]: task/index.html#blocking-and-yielding\n\nThe [`tokio::sync`] module contains synchronization primitives to use when\nneeding to communicate or share data. These include:\n\n* channels ([`oneshot`], [`mpsc`], [`watch`], and [`broadcast`]), for sending values\n between tasks,\n* a non-blocking [`Mutex`], for controlling access to a shared, mutable\n value,\n* an asynchronous [`Barrier`] type, for multiple tasks to synchronize before\n beginning a computation.\n\nThe `tokio::sync` module is present only when the \"sync\" feature flag is\nenabled.\n\n[`tokio::sync`]: crate::sync\n[`Mutex`]: crate::sync::Mutex\n[`Barrier`]: crate::sync::Barrier\n[`oneshot`]: crate::sync::oneshot\n[`mpsc`]: crate::sync::mpsc\n[`watch`]: crate::sync::watch\n[`broadcast`]: crate::sync::broadcast\n\nThe [`tokio::time`] module provides utilities for tracking time and\nscheduling work. This includes functions for setting [timeouts][timeout] for\ntasks, [sleeping][sleep] work to run in the future, or [repeating an operation at an\ninterval][interval].\n\nIn order to use `tokio::time`, the \"time\" feature flag must be enabled.\n\n[`tokio::time`]: crate::time\n[sleep]: crate::time::sleep()\n[interval]: crate::time::interval()\n[timeout]: crate::time::timeout()\n\nFinally, Tokio provides a _runtime_ for executing asynchronous tasks. Most\napplications can use the [`#[tokio::main]`][main] macro to run their code on the\nTokio runtime. However, this macro provides only basic configuration options. As\nan alternative, the [`tokio::runtime`] module provides more powerful APIs for configuring\nand managing runtimes. You should use that module if the `#[tokio::main]` macro doesn't\nprovide the functionality you need.\n\nUsing the runtime requires the \"rt\" or \"rt-multi-thread\" feature flags, to\nenable the basic [single-threaded scheduler][rt] and the [thread-pool\nscheduler][rt-multi-thread], respectively. See the [`runtime` module\ndocumentation][rt-features] for details. In addition, the \"macros\" feature\nflag enables the `#[tokio::main]` and `#[tokio::test]` attributes.\n\n[main]: attr.main.html\n[`tokio::runtime`]: crate::runtime\n[`Builder`]: crate::runtime::Builder\n[`Runtime`]: crate::runtime::Runtime\n[rt]: runtime/index.html#current-thread-scheduler\n[rt-multi-thread]: runtime/index.html#multi-thread-scheduler\n[rt-features]: runtime/index.html#runtime-scheduler\n\n## CPU-bound tasks and blocking code\n\nTokio is able to concurrently run many tasks on a few threads by repeatedly\nswapping the currently running task on each thread. However, this kind of\nswapping can only happen at `.await` points, so code that spends a long time\nwithout reaching an `.await` will prevent other tasks from running. To\ncombat this, Tokio provides two kinds of threads: Core threads and blocking\nthreads. The core threads are where all asynchronous code runs, and Tokio\nwill by default spawn one for each CPU core. The blocking threads are\nspawned on demand, can be used to run blocking code that would otherwise\nblock other tasks from running and are kept alive when not used for a certain\namount of time which can be configured with [`thread_keep_alive`].\nSince it is not possible for Tokio to swap out blocking tasks, like it\ncan do with asynchronous code, the upper limit on the number of blocking\nthreads is very large. These limits can be configured on the [`Builder`].\n\nTo spawn a blocking task, you should use the [`spawn_blocking`] function.\n\n[`Builder`]: crate::runtime::Builder\n[`spawn_blocking`]: crate::task::spawn_blocking()\n[`thread_keep_alive`]: crate::runtime::Builder::thread_keep_alive()\n\n```rust\n#[tokio::main]\nasync fn main() {\n // This is running on a core thread.\n\n let blocking_task = tokio::task::spawn_blocking(|| {\n // This is running on a blocking thread.\n // Blocking here is ok.\n });\n\n // We can wait for the blocking task like this:\n // If the blocking task panics, the unwrap below will propagate the\n // panic.\n blocking_task.await.unwrap();\n}\n```\n\nIf your code is CPU-bound and you wish to limit the number of threads used\nto run it, you should use a separate thread pool dedicated to CPU bound tasks.\nFor example, you could consider using the [rayon] library for CPU-bound\ntasks. It is also possible to create an extra Tokio runtime dedicated to\nCPU-bound tasks, but if you do this, you should be careful that the extra\nruntime runs _only_ CPU-bound tasks, as IO-bound tasks on that runtime\nwill behave poorly.\n\nHint: If using rayon, you can use a [`oneshot`] channel to send the result back\nto Tokio when the rayon task finishes.\n\n[rayon]: https://docs.rs/rayon\n[`oneshot`]: crate::sync::oneshot\n\n## Asynchronous IO\n\nAs well as scheduling and running tasks, Tokio provides everything you need\nto perform input and output asynchronously.\n\nThe [`tokio::io`] module provides Tokio's asynchronous core I/O primitives,\nthe [`AsyncRead`], [`AsyncWrite`], and [`AsyncBufRead`] traits. In addition,\nwhen the \"io-util\" feature flag is enabled, it also provides combinators and\nfunctions for working with these traits, forming as an asynchronous\ncounterpart to [`std::io`].\n\nTokio also includes APIs for performing various kinds of I/O and interacting\nwith the operating system asynchronously. These include:\n\n* [`tokio::net`], which contains non-blocking versions of [TCP], [UDP], and\n [Unix Domain Sockets][UDS] (enabled by the \"net\" feature flag),\n* [`tokio::fs`], similar to [`std::fs`] but for performing filesystem I/O\n asynchronously (enabled by the \"fs\" feature flag),\n* [`tokio::signal`], for asynchronously handling Unix and Windows OS signals\n (enabled by the \"signal\" feature flag),\n* [`tokio::process`], for spawning and managing child processes (enabled by\n the \"process\" feature flag).\n\n[`tokio::io`]: crate::io\n[`AsyncRead`]: crate::io::AsyncRead\n[`AsyncWrite`]: crate::io::AsyncWrite\n[`AsyncBufRead`]: crate::io::AsyncBufRead\n[`std::io`]: std::io\n[`tokio::net`]: crate::net\n[TCP]: crate::net::tcp\n[UDP]: crate::net::UdpSocket\n[UDS]: crate::net::unix\n[`tokio::fs`]: crate::fs\n[`std::fs`]: std::fs\n[`tokio::signal`]: crate::signal\n[`tokio::process`]: crate::process\n\n# Examples\n\nA simple TCP echo server:\n\n```rust\nuse tokio::net::TcpListener;\nuse tokio::io::{AsyncReadExt, AsyncWriteExt};\n\n#[tokio::main]\nasync fn main() -> Result<(), Box<dyn std::error::Error>> {\n let listener = TcpListener::bind(\"127.0.0.1:8080\").await?;\n\n loop {\n let (mut socket, _) = listener.accept().await?;\n\n tokio::spawn(async move {\n let mut buf = [0; 1024];\n\n // In a loop, read data from the socket and write the data back.\n loop {\n let n = match socket.read(&mut buf).await {\n // socket closed\n Ok(n) if n == 0 => return,\n Ok(n) => n,\n Err(e) => {\n eprintln!(\"failed to read from socket; err = {:?}\", e);\n return;\n }\n };\n\n // Write the data back\n if let Err(e) = socket.write_all(&buf[0..n]).await {\n eprintln!(\"failed to write to socket; err = {:?}\", e);\n return;\n }\n }\n });\n }\n}\n```\n\n## Feature flags\n\nTokio uses a set of [feature flags] to reduce the amount of compiled code. It\nis possible to just enable certain features over others. By default, Tokio\ndoes not enable any features but allows one to enable a subset for their use\ncase. Below is a list of the available feature flags. You may also notice\nabove each function, struct and trait there is listed one or more feature flags\nthat are required for that item to be used. If you are new to Tokio it is\nrecommended that you use the `full` feature flag which will enable all public APIs.\nBeware though that this will pull in many extra dependencies that you may not\nneed.\n\n- `full`: Enables all features listed below except `test-util` and `tracing`.\n- `rt`: Enables `tokio::spawn`, the basic (current thread) scheduler,\n and non-scheduler utilities.\n- `rt-multi-thread`: Enables the heavier, multi-threaded, work-stealing scheduler.\n- `io-util`: Enables the IO based `Ext` traits.\n- `io-std`: Enable `Stdout`, `Stdin` and `Stderr` types.\n- `net`: Enables `tokio::net` types such as `TcpStream`, `UnixStream` and\n `UdpSocket`, as well as (on Unix-like systems) `AsyncFd` and (on\n FreeBSD) `PollAio`.\n- `time`: Enables `tokio::time` types and allows the schedulers to enable\n the built in timer.\n- `process`: Enables `tokio::process` types.\n- `macros`: Enables `#[tokio::main]` and `#[tokio::test]` macros.\n- `sync`: Enables all `tokio::sync` types.\n- `signal`: Enables all `tokio::signal` types.\n- `fs`: Enables `tokio::fs` types.\n- `test-util`: Enables testing based infrastructure for the Tokio runtime.\n\n_Note: `AsyncRead` and `AsyncWrite` traits do not require any features and are\nalways available._\n\n### Internal features\n\nThese features do not expose any new API, but influence internal\nimplementation aspects of Tokio, and can pull in additional\ndependencies.\n\n- `parking_lot`: As a potential optimization, use the _parking_lot_ crate's\nsynchronization primitives internally. MSRV may increase according to the\n_parking_lot_ release in use.\n\n### Unstable features\n\nSome feature flags are only available when specifying the `tokio_unstable` flag:\n\n- `tracing`: Enables tracing events.\n\nLikewise, some parts of the API are only available with the same flag:\n\n- [`task::JoinSet`]\n- [`task::Builder`]\n\nThis flag enables **unstable** features. The public API of these features\nmay break in 1.x releases. To enable these features, the `--cfg\ntokio_unstable` argument must be passed to `rustc` when compiling. This\nserves to explicitly opt-in to features which may break semver conventions,\nsince Cargo [does not yet directly support such opt-ins][unstable features].\n\nYou can specify it in your project's `.cargo/config.toml` file:\n\n```toml\n[build]\nrustflags = [\"--cfg\", \"tokio_unstable\"]\n```\n\nAlternatively, you can specify it with an environment variable:\n\n```sh\n# Many *nix shells:\nexport RUSTFLAGS=\"--cfg tokio_unstable\"\ncargo build\n```\n\n```powershell\n# Windows PowerShell:\n$Env:RUSTFLAGS=\"--cfg tokio_unstable\"\ncargo build\n```\n\n[unstable features]: https://internals.rust-lang.org/t/feature-request-unstable-opt-in-non-transitive-crate-features/16193#why-not-a-crate-feature-2\n[feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section" }, filterText = "tokio", kind = 9, label = "tokio", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "tokio", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "A support library for macro authors when defining new macros.\n\nThis library, provided by the standard distribution, provides the types\nconsumed in the interfaces of procedurally defined macro definitions such as\nfunction-like macros `#[proc_macro]`, macro attributes `#[proc_macro_attribute]` and\ncustom derive attributes`#[proc_macro_derive]`.\n\nSee [the book] for more.\n\n[the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes" }, filterText = "proc_macro", kind = 9, label = "proc_macro", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "proc_macro", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "[![github]](https://github.com/dtolnay/syn)&ensp;[![crates-io]](https://crates.io/crates/syn)&ensp;[![docs-rs]](crate)\n\n[github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github\n[crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust\n[docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K\n\n<br>\n\nSyn is a parsing library for parsing a stream of Rust tokens into a syntax\ntree of Rust source code.\n\nCurrently this library is geared toward use in Rust procedural macros, but\ncontains some APIs that may be useful more generally.\n\n- **Data structures** — Syn provides a complete syntax tree that can\n represent any valid Rust source code. The syntax tree is rooted at\n [`syn::File`] which represents a full source file, but there are other\n entry points that may be useful to procedural macros including\n [`syn::Item`], [`syn::Expr`] and [`syn::Type`].\n\n- **Derives** — Of particular interest to derive macros is\n [`syn::DeriveInput`] which is any of the three legal input items to a\n derive macro. An example below shows using this type in a library that can\n derive implementations of a user-defined trait.\n\n- **Parsing** — Parsing in Syn is built around [parser functions] with the\n signature `fn(ParseStream) -> Result<T>`. Every syntax tree node defined\n by Syn is individually parsable and may be used as a building block for\n custom syntaxes, or you may dream up your own brand new syntax without\n involving any of our syntax tree types.\n\n- **Location information** — Every token parsed by Syn is associated with a\n `Span` that tracks line and column information back to the source of that\n token. These spans allow a procedural macro to display detailed error\n messages pointing to all the right places in the user's code. There is an\n example of this below.\n\n- **Feature flags** — Functionality is aggressively feature gated so your\n procedural macros enable only what they need, and do not pay in compile\n time for all the rest.\n\n[`syn::File`]: File\n[`syn::Item`]: Item\n[`syn::Expr`]: Expr\n[`syn::Type`]: Type\n[`syn::DeriveInput`]: DeriveInput\n[parser functions]: mod@parse\n\n<br>\n\n# Example of a derive macro\n\nThe canonical derive macro using Syn looks like this. We write an ordinary\nRust function tagged with a `proc_macro_derive` attribute and the name of\nthe trait we are deriving. Any time that derive appears in the user's code,\nthe Rust compiler passes their data structure as tokens into our macro. We\nget to execute arbitrary Rust code to figure out what to do with those\ntokens, then hand some tokens back to the compiler to compile into the\nuser's crate.\n\n[`TokenStream`]: proc_macro::TokenStream\n\n```toml\n[dependencies]\nsyn = \"1.0\"\nquote = \"1.0\"\n\n[lib]\nproc-macro = true\n```\n\n```rust\nuse proc_macro::TokenStream;\nuse quote::quote;\nuse syn::{parse_macro_input, DeriveInput};\n\n#[proc_macro_derive(MyMacro)]\npub fn my_macro(input: TokenStream) -> TokenStream {\n // Parse the input tokens into a syntax tree\n let input = parse_macro_input!(input as DeriveInput);\n\n // Build the output, possibly using quasi-quotation\n let expanded = quote! {\n // ...\n };\n\n // Hand the output tokens back to the compiler\n TokenStream::from(expanded)\n}\n```\n\nThe [`heapsize`] example directory shows a complete working implementation\nof a derive macro. It works on any Rust compiler 1.31+. The example derives\na `HeapSize` trait which computes an estimate of the amount of heap memory\nowned by a value.\n\n[`heapsize`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize\n\n```rust\npub trait HeapSize {\n /// Total number of bytes of heap memory owned by `self`.\n fn heap_size_of_children(&self) -> usize;\n}\n```\n\nThe derive macro allows users to write `#[derive(HeapSize)]` on data\nstructures in their program.\n\n```rust\n#[derive(HeapSize)]\nstruct Demo<'a, T: ?Sized> {\n a: Box<T>,\n b: u8,\n c: &'a str,\n d: String,\n}\n```\n\n<p><br></p>\n\n# Spans and error reporting\n\nThe token-based procedural macro API provides great control over where the\ncompiler's error messages are displayed in user code. Consider the error the\nuser sees if one of their field types does not implement `HeapSize`.\n\n```rust\n#[derive(HeapSize)]\nstruct Broken {\n ok: String,\n bad: std::thread::Thread,\n}\n```\n\nBy tracking span information all the way through the expansion of a\nprocedural macro as shown in the `heapsize` example, token-based macros in\nSyn are able to trigger errors that directly pinpoint the source of the\nproblem.\n\n```text\nerror[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied\n --> src/main.rs:7:5\n |\n7 | bad: std::thread::Thread,\n | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `Thread`\n```\n\n<br>\n\n# Parsing a custom syntax\n\nThe [`lazy-static`] example directory shows the implementation of a\n`functionlike!(...)` procedural macro in which the input tokens are parsed\nusing Syn's parsing API.\n\n[`lazy-static`]: https://github.com/dtolnay/syn/tree/master/examples/lazy-static\n\nThe example reimplements the popular `lazy_static` crate from crates.io as a\nprocedural macro.\n\n```rust\nlazy_static! {\n static ref USERNAME: Regex = Regex::new(\"^[a-z0-9_-]{3,16}$\").unwrap();\n}\n```\n\nThe implementation shows how to trigger custom warnings and error messages\non the macro input.\n\n```text\nwarning: come on, pick a more creative name\n --> src/main.rs:10:16\n |\n10 | static ref FOO: String = \"lazy_static\".to_owned();\n | ^^^\n```\n\n<br>\n\n# Testing\n\nWhen testing macros, we often care not just that the macro can be used\nsuccessfully but also that when the macro is provided with invalid input it\nproduces maximally helpful error messages. Consider using the [`trybuild`]\ncrate to write tests for errors that are emitted by your macro or errors\ndetected by the Rust compiler in the expanded code following misuse of the\nmacro. Such tests help avoid regressions from later refactors that\nmistakenly make an error no longer trigger or be less helpful than it used\nto be.\n\n[`trybuild`]: https://github.com/dtolnay/trybuild\n\n<br>\n\n# Debugging\n\nWhen developing a procedural macro it can be helpful to look at what the\ngenerated code looks like. Use `cargo rustc -- -Zunstable-options\n--pretty=expanded` or the [`cargo expand`] subcommand.\n\n[`cargo expand`]: https://github.com/dtolnay/cargo-expand\n\nTo show the expanded code for some crate that uses your procedural macro,\nrun `cargo expand` from that crate. To show the expanded code for one of\nyour own test cases, run `cargo expand --test the_test_case` where the last\nargument is the name of the test file without the `.rs` extension.\n\nThis write-up by Brandon W Maister discusses debugging in more detail:\n[Debugging Rust's new Custom Derive system][debugging].\n\n[debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/\n\n<br>\n\n# Optional features\n\nSyn puts a lot of functionality behind optional features in order to\noptimize compile time for the most common use cases. The following features\nare available.\n\n- **`derive`** *(enabled by default)* — Data structures for representing the\n possible input to a derive macro, including structs and enums and types.\n- **`full`** — Data structures for representing the syntax tree of all valid\n Rust source code, including items and expressions.\n- **`parsing`** *(enabled by default)* — Ability to parse input tokens into\n a syntax tree node of a chosen type.\n- **`printing`** *(enabled by default)* — Ability to print a syntax tree\n node as tokens of Rust source code.\n- **`visit`** — Trait for traversing a syntax tree.\n- **`visit-mut`** — Trait for traversing and mutating in place a syntax\n tree.\n- **`fold`** — Trait for transforming an owned syntax tree.\n- **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree\n types.\n- **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree\n types.\n- **`proc-macro`** *(enabled by default)* — Runtime dependency on the\n dynamic library libproc_macro from rustc toolchain." }, filterText = "syn", kind = 9, label = "syn", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "syn", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "u32", kind = 22, label = "u32", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "u32", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "bool", kind = 22, label = "bool", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "bool", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "u8", kind = 22, label = "u8", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "u8", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "isize", kind = 22, label = "isize", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "isize", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "u16", kind = 22, label = "u16", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "u16", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "u64", kind = 22, label = "u64", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "u64", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "u128", kind = 22, label = "u128", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "u128", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "f32", kind = 22, label = "f32", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "f32", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "i128", kind = 22, label = "i128", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "i128", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "i16", kind = 22, label = "i16", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "i16", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "str", kind = 22, label = "str", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "str", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "i64", kind = 22, label = "i64", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "i64", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "char", kind = 22, label = "char", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "char", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "f64", kind = 22, label = "f64", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "f64", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "i32", kind = 22, label = "i32", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "i32", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "i8", kind = 22, label = "i8", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "i8", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "usize", kind = 22, label = "usize", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "usize", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Used to do a cheap mutable-to-mutable reference conversion.\n\nThis trait is similar to [`AsRef`] but used for converting between mutable\nreferences. If you need to do a costly conversion it is better to\nimplement [`From`] with type `&mut T` or write a custom function.\n\n**Note: This trait must not fail**. If the conversion can fail, use a\ndedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].\n\n# Generic Implementations\n\n- `AsMut` auto-dereferences if the inner type is a mutable reference\n (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo`\n or `&mut &mut Foo`)\n\n# Examples\n\nUsing `AsMut` as trait bound for a generic function we can accept all mutable references\nthat can be converted to type `&mut T`. Because [`Box<T>`] implements `AsMut<T>` we can\nwrite a function `add_one` that takes all arguments that can be converted to `&mut u64`.\nBecause [`Box<T>`] implements `AsMut<T>`, `add_one` accepts arguments of type\n`&mut Box<u64>` as well:\n\n```rust\nfn add_one<T: AsMut<u64>>(num: &mut T) {\n *num.as_mut() += 1;\n}\n\nlet mut boxed_num = Box::new(0);\nadd_one(&mut boxed_num);\nassert_eq!(*boxed_num, 1);\n```\n\n[`Box<T>`]: ../../std/boxed/struct.Box.html" }, filterText = "AsMut", kind = 8, label = "AsMut", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "AsMut", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "RustcDecodable", kind = 18, label = "RustcDecodable", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "RustcDecodable", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Used to do value-to-value conversions while consuming the input value. It is the reciprocal of\n[`Into`].\n\nOne should always prefer implementing `From` over [`Into`]\nbecause implementing `From` automatically provides one with an implementation of [`Into`]\nthanks to the blanket implementation in the standard library.\n\nOnly implement [`Into`] when targeting a version prior to Rust 1.41 and converting to a type\noutside the current crate.\n`From` was not able to do these types of conversions in earlier versions because of Rust's\norphaning rules.\nSee [`Into`] for more details.\n\nPrefer using [`Into`] over using `From` when specifying trait bounds on a generic function.\nThis way, types that directly implement [`Into`] can be used as arguments as well.\n\nThe `From` is also very useful when performing error handling. When constructing a function\nthat is capable of failing, the return type will generally be of the form `Result<T, E>`.\nThe `From` trait simplifies error handling by allowing a function to return a single error type\nthat encapsulate multiple error types. See the \"Examples\" section and [the book][book] for more\ndetails.\n\n**Note: This trait must not fail**. The `From` trait is intended for perfect conversions.\nIf the conversion can fail or is not perfect, use [`TryFrom`].\n\n# Generic Implementations\n\n- `From<T> for U` implies [`Into`]`<U> for T`\n- `From` is reflexive, which means that `From<T> for T` is implemented\n\n# Examples\n\n[`String`] implements `From<&str>`:\n\nAn explicit conversion from a `&str` to a String is done as follows:\n\n```rust\nlet string = \"hello\".to_string();\nlet other_string = String::from(\"hello\");\n\nassert_eq!(string, other_string);\n```\n\nWhile performing error handling it is often useful to implement `From` for your own error type.\nBy converting underlying error types to our own custom error type that encapsulates the\nunderlying error type, we can return a single error type without losing information on the\nunderlying cause. The '?' operator automatically converts the underlying error type to our\ncustom error type by calling `Into<CliError>::into` which is automatically provided when\nimplementing `From`. The compiler then infers which implementation of `Into` should be used.\n\n```rust\nuse std::fs;\nuse std::io;\nuse std::num;\n\nenum CliError {\n IoError(io::Error),\n ParseError(num::ParseIntError),\n}\n\nimpl From<io::Error> for CliError {\n fn from(error: io::Error) -> Self {\n CliError::IoError(error)\n }\n}\n\nimpl From<num::ParseIntError> for CliError {\n fn from(error: num::ParseIntError) -> Self {\n CliError::ParseError(error)\n }\n}\n\nfn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {\n let mut contents = fs::read_to_string(&file_name)?;\n let num: i32 = contents.trim().parse()?;\n Ok(num)\n}\n```\n\n[`String`]: ../../std/string/struct.String.html\n[`from`]: From::from\n[book]: ../../book/ch09-00-error-handling.html" }, filterText = "From", kind = 8, label = "From", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "From", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Types that can be safely moved after being pinned.\n\nRust itself has no notion of immovable types, and considers moves (e.g.,\nthrough assignment or [`mem::replace`]) to always be safe.\n\nThe [`Pin`][Pin] type is used instead to prevent moves through the type\nsystem. Pointers `P<T>` wrapped in the [`Pin<P<T>>`][Pin] wrapper can't be\nmoved out of. See the [`pin` module] documentation for more information on\npinning.\n\nImplementing the `Unpin` trait for `T` lifts the restrictions of pinning off\nthe type, which then allows moving `T` out of [`Pin<P<T>>`][Pin] with\nfunctions such as [`mem::replace`].\n\n`Unpin` has no consequence at all for non-pinned data. In particular,\n[`mem::replace`] happily moves `!Unpin` data (it works for any `&mut T`, not\njust when `T: Unpin`). However, you cannot use [`mem::replace`] on data\nwrapped inside a [`Pin<P<T>>`][Pin] because you cannot get the `&mut T` you\nneed for that, and *that* is what makes this system work.\n\nSo this, for example, can only be done on types implementing `Unpin`:\n\n```rust\nuse std::mem;\nuse std::pin::Pin;\n\nlet mut string = \"this\".to_string();\nlet mut pinned_string = Pin::new(&mut string);\n\n// We need a mutable reference to call `mem::replace`.\n// We can obtain such a reference by (implicitly) invoking `Pin::deref_mut`,\n// but that is only possible because `String` implements `Unpin`.\nmem::replace(&mut *pinned_string, \"other\".to_string());\n```\n\nThis trait is automatically implemented for almost every type.\n\n[`mem::replace`]: crate::mem::replace\n[Pin]: crate::pin::Pin\n[`pin` module]: crate::pin" }, filterText = "Unpin", kind = 8, label = "Unpin", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Unpin", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "The version of the call operator that takes a mutable receiver.\n\nInstances of `FnMut` can be called repeatedly and may mutate state.\n\n`FnMut` is implemented automatically by closures which take mutable\nreferences to captured variables, as well as all types that implement\n[`Fn`], e.g., (safe) [function pointers] (since `FnMut` is a supertrait of\n[`Fn`]). Additionally, for any type `F` that implements `FnMut`, `&mut F`\nimplements `FnMut`, too.\n\nSince [`FnOnce`] is a supertrait of `FnMut`, any instance of `FnMut` can be\nused where a [`FnOnce`] is expected, and since [`Fn`] is a subtrait of\n`FnMut`, any instance of [`Fn`] can be used where `FnMut` is expected.\n\nUse `FnMut` as a bound when you want to accept a parameter of function-like\ntype and need to call it repeatedly, while allowing it to mutate state.\nIf you don't want the parameter to mutate state, use [`Fn`] as a\nbound; if you don't need to call it repeatedly, use [`FnOnce`].\n\nSee the [chapter on closures in *The Rust Programming Language*][book] for\nsome more information on this topic.\n\nAlso of note is the special syntax for `Fn` traits (e.g.\n`Fn(usize, bool) -> usize`). Those interested in the technical details of\nthis can refer to [the relevant section in the *Rustonomicon*][nomicon].\n\n[book]: ../../book/ch13-01-closures.html\n[function pointers]: fn\n[nomicon]: ../../nomicon/hrtb.html\n\n# Examples\n\n## Calling a mutably capturing closure\n\n```rust\nlet mut x = 5;\n{\n let mut square_x = || x *= x;\n square_x();\n}\nassert_eq!(x, 25);\n```\n\n## Using a `FnMut` parameter\n\n```rust\nfn do_twice<F>(mut func: F)\n where F: FnMut()\n{\n func();\n func();\n}\n\nlet mut x: usize = 1;\n{\n let add_two_to_x = || x += 2;\n do_twice(add_two_to_x);\n}\n\nassert_eq!(x, 5);\n```" }, filterText = "FnMut", kind = 8, label = "FnMut", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "FnMut", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Extend a collection with the contents of an iterator.\n\nIterators produce a series of values, and collections can also be thought\nof as a series of values. The `Extend` trait bridges this gap, allowing you\nto extend a collection by including the contents of that iterator. When\nextending a collection with an already existing key, that entry is updated\nor, in the case of collections that permit multiple entries with equal\nkeys, that entry is inserted.\n\n# Examples\n\nBasic usage:\n\n```rust\n// You can extend a String with some chars:\nlet mut message = String::from(\"The first three letters are: \");\n\nmessage.extend(&['a', 'b', 'c']);\n\nassert_eq!(\"abc\", &message[29..32]);\n```\n\nImplementing `Extend`:\n\n```rust\n// A sample collection, that's just a wrapper over Vec<T>\n#[derive(Debug)]\nstruct MyCollection(Vec<i32>);\n\n// Let's give it some methods so we can create one and add things\n// to it.\nimpl MyCollection {\n fn new() -> MyCollection {\n MyCollection(Vec::new())\n }\n\n fn add(&mut self, elem: i32) {\n self.0.push(elem);\n }\n}\n\n// since MyCollection has a list of i32s, we implement Extend for i32\nimpl Extend<i32> for MyCollection {\n\n // This is a bit simpler with the concrete type signature: we can call\n // extend on anything which can be turned into an Iterator which gives\n // us i32s. Because we need i32s to put into MyCollection.\n fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {\n\n // The implementation is very straightforward: loop through the\n // iterator, and add() each element to ourselves.\n for elem in iter {\n self.add(elem);\n }\n }\n}\n\nlet mut c = MyCollection::new();\n\nc.add(5);\nc.add(6);\nc.add(7);\n\n// let's extend our collection with three more numbers\nc.extend(vec![1, 2, 3]);\n\n// we've added these elements onto the end\nassert_eq!(\"MyCollection([5, 6, 7, 1, 2, 3])\", format!(\"{c:?}\"));\n```" }, filterText = "Extend", kind = 8, label = "Extend", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Extend", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Trait for equality comparisons which are [partial equivalence\nrelations](https://en.wikipedia.org/wiki/Partial_equivalence_relation).\n\n`x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.\nWe use the easier-to-read infix notation in the remainder of this documentation.\n\nThis trait allows for partial equality, for types that do not have a full\nequivalence relation. For example, in floating point numbers `NaN != NaN`,\nso floating point types implement `PartialEq` but not [`trait@Eq`].\n\nImplementations must ensure that `eq` and `ne` are consistent with each other:\n\n- `a != b` if and only if `!(a == b)`\n (ensured by the default implementation).\n\nIf [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also\nbe consistent with `PartialEq` (see the documentation of those traits for the exact\nrequirements). It's easy to accidentally make them disagree by deriving some of the traits and\nmanually implementing others.\n\nThe equality relation `==` must satisfy the following conditions\n(for all `a`, `b`, `c` of type `A`, `B`, `C`):\n\n- **Symmetric**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`\n implies `b == a`**; and\n\n- **Transitive**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:\n PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.\n\nNote that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`\n(transitive) impls are not forced to exist, but these requirements apply\nwhenever they do exist.\n\n## Derivable\n\nThis trait can be used with `#[derive]`. When `derive`d on structs, two\ninstances are equal if all fields are equal, and not equal if any fields\nare not equal. When `derive`d on enums, each variant is equal to itself\nand not equal to the other variants.\n\n## How can I implement `PartialEq`?\n\nAn example implementation for a domain in which two books are considered\nthe same book if their ISBN matches, even if the formats differ:\n\n```rust\nenum BookFormat {\n Paperback,\n Hardback,\n Ebook,\n}\n\nstruct Book {\n isbn: i32,\n format: BookFormat,\n}\n\nimpl PartialEq for Book {\n fn eq(&self, other: &Self) -> bool {\n self.isbn == other.isbn\n }\n}\n\nlet b1 = Book { isbn: 3, format: BookFormat::Paperback };\nlet b2 = Book { isbn: 3, format: BookFormat::Ebook };\nlet b3 = Book { isbn: 10, format: BookFormat::Paperback };\n\nassert!(b1 == b2);\nassert!(b1 != b3);\n```\n\n## How can I compare two different types?\n\nThe type you can compare with is controlled by `PartialEq`'s type parameter.\nFor example, let's tweak our previous code a bit:\n\n```rust\n// The derive implements <BookFormat> == <BookFormat> comparisons\n#[derive(PartialEq)]\nenum BookFormat {\n Paperback,\n Hardback,\n Ebook,\n}\n\nstruct Book {\n isbn: i32,\n format: BookFormat,\n}\n\n// Implement <Book> == <BookFormat> comparisons\nimpl PartialEq<BookFormat> for Book {\n fn eq(&self, other: &BookFormat) -> bool {\n self.format == *other\n }\n}\n\n// Implement <BookFormat> == <Book> comparisons\nimpl PartialEq<Book> for BookFormat {\n fn eq(&self, other: &Book) -> bool {\n *self == other.format\n }\n}\n\nlet b1 = Book { isbn: 3, format: BookFormat::Paperback };\n\nassert!(b1 == BookFormat::Paperback);\nassert!(BookFormat::Ebook != b1);\n```\n\nBy changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,\nwe allow `BookFormat`s to be compared with `Book`s.\n\nA comparison like the one above, which ignores some fields of the struct,\ncan be dangerous. It can easily lead to an unintended violation of the\nrequirements for a partial equivalence relation. For example, if we kept\nthe above implementation of `PartialEq<Book>` for `BookFormat` and added an\nimplementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or\nvia the manual implementation from the first example) then the result would\nviolate transitivity:\n\n```rust\n#[derive(PartialEq)]\nenum BookFormat {\n Paperback,\n Hardback,\n Ebook,\n}\n\n#[derive(PartialEq)]\nstruct Book {\n isbn: i32,\n format: BookFormat,\n}\n\nimpl PartialEq<BookFormat> for Book {\n fn eq(&self, other: &BookFormat) -> bool {\n self.format == *other\n }\n}\n\nimpl PartialEq<Book> for BookFormat {\n fn eq(&self, other: &Book) -> bool {\n *self == other.format\n }\n}\n\nfn main() {\n let b1 = Book { isbn: 1, format: BookFormat::Paperback };\n let b2 = Book { isbn: 2, format: BookFormat::Paperback };\n\n assert!(b1 == BookFormat::Paperback);\n assert!(BookFormat::Paperback == b2);\n\n // The following should hold by transitivity but doesn't.\n assert!(b1 == b2); // <-- PANICS\n}\n```\n\n# Examples\n\n```rust\nlet x: u32 = 0;\nlet y: u32 = 1;\n\nassert_eq!(x == y, false);\nassert_eq!(x.eq(&y), false);\n```\n\n[`eq`]: PartialEq::eq\n[`ne`]: PartialEq::ne" }, filterText = "PartialEq", kind = 8, label = "PartialEq", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "PartialEq", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, filterText = "RustcEncodable", kind = 18, label = "RustcEncodable", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "RustcEncodable", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Custom code within the destructor.\n\nWhen a value is no longer needed, Rust will run a \"destructor\" on that value.\nThe most common way that a value is no longer needed is when it goes out of\nscope. Destructors may still run in other circumstances, but we're going to\nfocus on scope for the examples here. To learn about some of those other cases,\nplease see [the reference] section on destructors.\n\n[the reference]: https://doc.rust-lang.org/reference/destructors.html\n\nThis destructor consists of two components:\n- A call to `Drop::drop` for that value, if this special `Drop` trait is implemented for its type.\n- The automatically generated \"drop glue\" which recursively calls the destructors\n of all the fields of this value.\n\nAs Rust automatically calls the destructors of all contained fields,\nyou don't have to implement `Drop` in most cases. But there are some cases where\nit is useful, for example for types which directly manage a resource.\nThat resource may be memory, it may be a file descriptor, it may be a network socket.\nOnce a value of that type is no longer going to be used, it should \"clean up\" its\nresource by freeing the memory or closing the file or socket. This is\nthe job of a destructor, and therefore the job of `Drop::drop`.\n\n## Examples\n\nTo see destructors in action, let's take a look at the following program:\n\n```rust\nstruct HasDrop;\n\nimpl Drop for HasDrop {\n fn drop(&mut self) {\n println!(\"Dropping HasDrop!\");\n }\n}\n\nstruct HasTwoDrops {\n one: HasDrop,\n two: HasDrop,\n}\n\nimpl Drop for HasTwoDrops {\n fn drop(&mut self) {\n println!(\"Dropping HasTwoDrops!\");\n }\n}\n\nfn main() {\n let _x = HasTwoDrops { one: HasDrop, two: HasDrop };\n println!(\"Running!\");\n}\n```\n\nRust will first call `Drop::drop` for `_x` and then for both `_x.one` and `_x.two`,\nmeaning that running this will print\n\n```text\nRunning!\nDropping HasTwoDrops!\nDropping HasDrop!\nDropping HasDrop!\n```\n\nEven if we remove the implementation of `Drop` for `HasTwoDrop`, the destructors of its fields are still called.\nThis would result in\n\n```test\nRunning!\nDropping HasDrop!\nDropping HasDrop!\n```\n\n## You cannot call `Drop::drop` yourself\n\nBecause `Drop::drop` is used to clean up a value, it may be dangerous to use this value after\nthe method has been called. As `Drop::drop` does not take ownership of its input,\nRust prevents misuse by not allowing you to call `Drop::drop` directly.\n\nIn other words, if you tried to explicitly call `Drop::drop` in the above example, you'd get a compiler error.\n\nIf you'd like to explicitly call the destructor of a value, [`mem::drop`] can be used instead.\n\n[`mem::drop`]: drop\n\n## Drop order\n\nWhich of our two `HasDrop` drops first, though? For structs, it's the same\norder that they're declared: first `one`, then `two`. If you'd like to try\nthis yourself, you can modify `HasDrop` above to contain some data, like an\ninteger, and then use it in the `println!` inside of `Drop`. This behavior is\nguaranteed by the language.\n\nUnlike for structs, local variables are dropped in reverse order:\n\n```rust\nstruct Foo;\n\nimpl Drop for Foo {\n fn drop(&mut self) {\n println!(\"Dropping Foo!\")\n }\n}\n\nstruct Bar;\n\nimpl Drop for Bar {\n fn drop(&mut self) {\n println!(\"Dropping Bar!\")\n }\n}\n\nfn main() {\n let _foo = Foo;\n let _bar = Bar;\n}\n```\n\nThis will print\n\n```text\nDropping Bar!\nDropping Foo!\n```\n\nPlease see [the reference] for the full rules.\n\n[the reference]: https://doc.rust-lang.org/reference/destructors.html\n\n## `Copy` and `Drop` are exclusive\n\nYou cannot implement both [`Copy`] and `Drop` on the same type. Types that\nare `Copy` get implicitly duplicated by the compiler, making it very\nhard to predict when, and how often destructors will be executed. As such,\nthese types cannot have destructors." }, filterText = "Drop", kind = 8, label = "Drop", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Drop", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "A trait for converting a value to a `String`.\n\nThis trait is automatically implemented for any type which implements the\n[`Display`] trait. As such, `ToString` shouldn't be implemented directly:\n[`Display`] should be implemented instead, and you get the `ToString`\nimplementation for free.\n\n[`Display`]: fmt::Display" }, filterText = "ToString", kind = 8, label = "ToString", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "ToString", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).\n\nThe `lt`, `le`, `gt`, and `ge` methods of this trait can be called using\nthe `<`, `<=`, `>`, and `>=` operators, respectively.\n\nThe methods of this trait must be consistent with each other and with those of [`PartialEq`].\nThe following conditions must hold:\n\n1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.\n2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`\n3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`\n4. `a <= b` if and only if `a < b || a == b`\n5. `a >= b` if and only if `a > b || a == b`\n6. `a != b` if and only if `!(a == b)`.\n\nConditions 2–5 above are ensured by the default implementation.\nCondition 6 is already ensured by [`PartialEq`].\n\nIf [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with\n`partial_cmp` (see the documentation of that trait for the exact requirements). It's\neasy to accidentally make them disagree by deriving some of the traits and manually\nimplementing others.\n\nThe comparison must satisfy, for all `a`, `b` and `c`:\n\n- transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.\n- duality: `a < b` if and only if `b > a`.\n\nNote that these requirements mean that the trait itself must be implemented symmetrically and\ntransitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:\nPartialOrd<V>`.\n\n## Corollaries\n\nThe following corollaries follow from the above requirements:\n\n- irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`\n- transitivity of `>`: if `a > b` and `b > c` then `a > c`\n- duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`\n\n## Derivable\n\nThis trait can be used with `#[derive]`.\n\nWhen `derive`d on structs, it will produce a\n[lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering\nbased on the top-to-bottom declaration order of the struct's members.\n\nWhen `derive`d on enums, variants are ordered by their discriminants.\nBy default, the discriminant is smallest for variants at the top, and\nlargest for variants at the bottom. Here's an example:\n\n```rust\n#[derive(PartialEq, PartialOrd)]\nenum E {\n Top,\n Bottom,\n}\n\nassert!(E::Top < E::Bottom);\n```\n\nHowever, manually setting the discriminants can override this default\nbehavior:\n\n```rust\n#[derive(PartialEq, PartialOrd)]\nenum E {\n Top = 2,\n Bottom = 1,\n}\n\nassert!(E::Bottom < E::Top);\n```\n\n## How can I implement `PartialOrd`?\n\n`PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others\ngenerated from default implementations.\n\nHowever it remains possible to implement the others separately for types which do not have a\ntotal order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==\nfalse` (cf. IEEE 754-2008 section 5.11).\n\n`PartialOrd` requires your type to be [`PartialEq`].\n\nIf your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:\n\n```rust\nuse std::cmp::Ordering;\n\n#[derive(Eq)]\nstruct Person {\n id: u32,\n name: String,\n height: u32,\n}\n\nimpl PartialOrd for Person {\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n Some(self.cmp(other))\n }\n}\n\nimpl Ord for Person {\n fn cmp(&self, other: &Self) -> Ordering {\n self.height.cmp(&other.height)\n }\n}\n\nimpl PartialEq for Person {\n fn eq(&self, other: &Self) -> bool {\n self.height == other.height\n }\n}\n```\n\nYou may also find it useful to use [`partial_cmp`] on your type's fields. Here\nis an example of `Person` types who have a floating-point `height` field that\nis the only field to be used for sorting:\n\n```rust\nuse std::cmp::Ordering;\n\nstruct Person {\n id: u32,\n name: String,\n height: f64,\n}\n\nimpl PartialOrd for Person {\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n self.height.partial_cmp(&other.height)\n }\n}\n\nimpl PartialEq for Person {\n fn eq(&self, other: &Self) -> bool {\n self.height == other.height\n }\n}\n```\n\n# Examples\n\n```rust\nlet x: u32 = 0;\nlet y: u32 = 1;\n\nassert_eq!(x < y, true);\nassert_eq!(x.lt(&y), true);\n```\n\n[`partial_cmp`]: PartialOrd::partial_cmp\n[`cmp`]: Ord::cmp" }, filterText = "PartialOrd", kind = 8, label = "PartialOrd", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "PartialOrd", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, command = { command = "editor.action.triggerParameterHints", title = "triggerParameterHints" }, deprecated = false, documentation = { kind = "markdown", value = "The `Option` type. See [the module level documentation](self) for more." }, filterText = "Option", insertTextFormat = 2, kind = 13, label = "Option<…>", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Option<$0>", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Types whose values can be duplicated simply by copying bits.\n\nBy default, variable bindings have 'move semantics.' In other\nwords:\n\n```rust\n#[derive(Debug)]\nstruct Foo;\n\nlet x = Foo;\n\nlet y = x;\n\n// `x` has moved into `y`, and so cannot be used\n\n// println!(\"{x:?}\"); // error: use of moved value\n```\n\nHowever, if a type implements `Copy`, it instead has 'copy semantics':\n\n```rust\n// We can derive a `Copy` implementation. `Clone` is also required, as it's\n// a supertrait of `Copy`.\n#[derive(Debug, Copy, Clone)]\nstruct Foo;\n\nlet x = Foo;\n\nlet y = x;\n\n// `y` is a copy of `x`\n\nprintln!(\"{x:?}\"); // A-OK!\n```\n\nIt's important to note that in these two examples, the only difference is whether you\nare allowed to access `x` after the assignment. Under the hood, both a copy and a move\ncan result in bits being copied in memory, although this is sometimes optimized away.\n\n## How can I implement `Copy`?\n\nThere are two ways to implement `Copy` on your type. The simplest is to use `derive`:\n\n```rust\n#[derive(Copy, Clone)]\nstruct MyStruct;\n```\n\nYou can also implement `Copy` and `Clone` manually:\n\n```rust\nstruct MyStruct;\n\nimpl Copy for MyStruct { }\n\nimpl Clone for MyStruct {\n fn clone(&self) -> MyStruct {\n *self\n }\n}\n```\n\nThere is a small difference between the two: the `derive` strategy will also place a `Copy`\nbound on type parameters, which isn't always desired.\n\n## What's the difference between `Copy` and `Clone`?\n\nCopies happen implicitly, for example as part of an assignment `y = x`. The behavior of\n`Copy` is not overloadable; it is always a simple bit-wise copy.\n\nCloning is an explicit action, `x.clone()`. The implementation of [`Clone`] can\nprovide any type-specific behavior necessary to duplicate values safely. For example,\nthe implementation of [`Clone`] for [`String`] needs to copy the pointed-to string\nbuffer in the heap. A simple bitwise copy of [`String`] values would merely copy the\npointer, leading to a double free down the line. For this reason, [`String`] is [`Clone`]\nbut not `Copy`.\n\n[`Clone`] is a supertrait of `Copy`, so everything which is `Copy` must also implement\n[`Clone`]. If a type is `Copy` then its [`Clone`] implementation only needs to return `*self`\n(see the example above).\n\n## When can my type be `Copy`?\n\nA type can implement `Copy` if all of its components implement `Copy`. For example, this\nstruct can be `Copy`:\n\n```rust\n#[derive(Copy, Clone)]\nstruct Point {\n x: i32,\n y: i32,\n}\n```\n\nA struct can be `Copy`, and [`i32`] is `Copy`, therefore `Point` is eligible to be `Copy`.\nBy contrast, consider\n\n```rust\nstruct PointList {\n points: Vec<Point>,\n}\n```\n\nThe struct `PointList` cannot implement `Copy`, because [`Vec<T>`] is not `Copy`. If we\nattempt to derive a `Copy` implementation, we'll get an error:\n\n```text\nthe trait `Copy` may not be implemented for this type; field `points` does not implement `Copy`\n```\n\nShared references (`&T`) are also `Copy`, so a type can be `Copy`, even when it holds\nshared references of types `T` that are *not* `Copy`. Consider the following struct,\nwhich can implement `Copy`, because it only holds a *shared reference* to our non-`Copy`\ntype `PointList` from above:\n\n```rust\n#[derive(Copy, Clone)]\nstruct PointListWrapper<'a> {\n point_list_ref: &'a PointList,\n}\n```\n\n## When *can't* my type be `Copy`?\n\nSome types can't be copied safely. For example, copying `&mut T` would create an aliased\nmutable reference. Copying [`String`] would duplicate responsibility for managing the\n[`String`]'s buffer, leading to a double free.\n\nGeneralizing the latter case, any type implementing [`Drop`] can't be `Copy`, because it's\nmanaging some resource besides its own [`size_of::<T>`] bytes.\n\nIf you try to implement `Copy` on a struct or enum containing non-`Copy` data, you will get\nthe error [E0204].\n\n[E0204]: ../../error-index.html#E0204\n\n## When *should* my type be `Copy`?\n\nGenerally speaking, if your type _can_ implement `Copy`, it should. Keep in mind, though,\nthat implementing `Copy` is part of the public API of your type. If the type might become\nnon-`Copy` in the future, it could be prudent to omit the `Copy` implementation now, to\navoid a breaking API change.\n\n## Additional implementors\n\nIn addition to the [implementors listed below][impls],\nthe following types also implement `Copy`:\n\n* Function item types (i.e., the distinct types defined for each function)\n* Function pointer types (e.g., `fn() -> i32`)\n* Tuple types, if each component also implements `Copy` (e.g., `()`, `(i32, bool)`)\n* Closure types, if they capture no value from the environment\n or if all such captured values implement `Copy` themselves.\n Note that variables captured by shared reference always implement `Copy`\n (even if the referent doesn't),\n while variables captured by mutable reference never implement `Copy`.\n\n[`Vec<T>`]: ../../std/vec/struct.Vec.html\n[`String`]: ../../std/string/struct.String.html\n[`size_of::<T>`]: crate::mem::size_of\n[impls]: #implementors" }, filterText = "Copy", kind = 8, label = "Copy", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Copy", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Simple and safe type conversions that may fail in a controlled\nway under some circumstances. It is the reciprocal of [`TryInto`].\n\nThis is useful when you are doing a type conversion that may\ntrivially succeed but may also need special handling.\nFor example, there is no way to convert an [`i64`] into an [`i32`]\nusing the [`From`] trait, because an [`i64`] may contain a value\nthat an [`i32`] cannot represent and so the conversion would lose data.\nThis might be handled by truncating the [`i64`] to an [`i32`] (essentially\ngiving the [`i64`]'s value modulo [`i32::MAX`]) or by simply returning\n[`i32::MAX`], or by some other method. The [`From`] trait is intended\nfor perfect conversions, so the `TryFrom` trait informs the\nprogrammer when a type conversion could go bad and lets them\ndecide how to handle it.\n\n# Generic Implementations\n\n- `TryFrom<T> for U` implies [`TryInto`]`<U> for T`\n- [`try_from`] is reflexive, which means that `TryFrom<T> for T`\nis implemented and cannot fail -- the associated `Error` type for\ncalling `T::try_from()` on a value of type `T` is [`Infallible`].\nWhen the [`!`] type is stabilized [`Infallible`] and [`!`] will be\nequivalent.\n\n`TryFrom<T>` can be implemented as follows:\n\n```rust\nstruct GreaterThanZero(i32);\n\nimpl TryFrom<i32> for GreaterThanZero {\n type Error = &'static str;\n\n fn try_from(value: i32) -> Result<Self, Self::Error> {\n if value <= 0 {\n Err(\"GreaterThanZero only accepts value superior than zero!\")\n } else {\n Ok(GreaterThanZero(value))\n }\n }\n}\n```\n\n# Examples\n\nAs described, [`i32`] implements `TryFrom<`[`i64`]`>`:\n\n```rust\nlet big_number = 1_000_000_000_000i64;\n// Silently truncates `big_number`, requires detecting\n// and handling the truncation after the fact.\nlet smaller_number = big_number as i32;\nassert_eq!(smaller_number, -727379968);\n\n// Returns an error because `big_number` is too big to\n// fit in an `i32`.\nlet try_smaller_number = i32::try_from(big_number);\nassert!(try_smaller_number.is_err());\n\n// Returns `Ok(3)`.\nlet try_successful_smaller_number = i32::try_from(3);\nassert!(try_successful_smaller_number.is_ok());\n```\n\n[`try_from`]: TryFrom::try_from" }, filterText = "TryFrom", kind = 8, label = "TryFrom", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "TryFrom", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "A UTF-8–encoded, growable string.\n\nThe `String` type is the most common string type that has ownership over the\ncontents of the string. It has a close relationship with its borrowed\ncounterpart, the primitive [`str`].\n\n# Examples\n\nYou can create a `String` from [a literal string][`&str`] with [`String::from`]:\n\n[`String::from`]: From::from\n\n```rust\nlet hello = String::from(\"Hello, world!\");\n```\n\nYou can append a [`char`] to a `String` with the [`push`] method, and\nappend a [`&str`] with the [`push_str`] method:\n\n```rust\nlet mut hello = String::from(\"Hello, \");\n\nhello.push('w');\nhello.push_str(\"orld!\");\n```\n\n[`push`]: String::push\n[`push_str`]: String::push_str\n\nIf you have a vector of UTF-8 bytes, you can create a `String` from it with\nthe [`from_utf8`] method:\n\n```rust\n// some bytes, in a vector\nlet sparkle_heart = vec![240, 159, 146, 150];\n\n// We know these bytes are valid, so we'll use `unwrap()`.\nlet sparkle_heart = String::from_utf8(sparkle_heart).unwrap();\n\nassert_eq!(\"💖\", sparkle_heart);\n```\n\n[`from_utf8`]: String::from_utf8\n\n# UTF-8\n\n`String`s are always valid UTF-8. If you need a non-UTF-8 string, consider\n[`OsString`]. It is similar, but without the UTF-8 constraint. Because UTF-8\nis a variable width encoding, `String`s are typically smaller than an array of\nthe same `chars`:\n\n```rust\nuse std::mem;\n\n// `s` is ASCII which represents each `char` as one byte\nlet s = \"hello\";\nassert_eq!(s.len(), 5);\n\n// A `char` array with the same contents would be longer because\n// every `char` is four bytes\nlet s = ['h', 'e', 'l', 'l', 'o'];\nlet size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum();\nassert_eq!(size, 20);\n\n// However, for non-ASCII strings, the difference will be smaller\n// and sometimes they are the same\nlet s = \"💖💖💖💖💖\";\nassert_eq!(s.len(), 20);\n\nlet s = ['💖', '💖', '💖', '💖', '💖'];\nlet size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum();\nassert_eq!(size, 20);\n```\n\nThis raises interesting questions as to how `s[i]` should work.\nWhat should `i` be here? Several options include byte indices and\n`char` indices but, because of UTF-8 encoding, only byte indices\nwould provide constant time indexing. Getting the `i`th `char`, for\nexample, is available using [`chars`]:\n\n```rust\nlet s = \"hello\";\nlet third_character = s.chars().nth(2);\nassert_eq!(third_character, Some('l'));\n\nlet s = \"💖💖💖💖💖\";\nlet third_character = s.chars().nth(2);\nassert_eq!(third_character, Some('💖'));\n```\n\nNext, what should `s[i]` return? Because indexing returns a reference\nto underlying data it could be `&u8`, `&[u8]`, or something else similar.\nSince we're only providing one index, `&u8` makes the most sense but that\nmight not be what the user expects and can be explicitly achieved with\n[`as_bytes()`]:\n\n```rust\n// The first byte is 104 - the byte value of `'h'`\nlet s = \"hello\";\nassert_eq!(s.as_bytes()[0], 104);\n// or\nassert_eq!(s.as_bytes()[0], b'h');\n\n// The first byte is 240 which isn't obviously useful\nlet s = \"💖💖💖💖💖\";\nassert_eq!(s.as_bytes()[0], 240);\n```\n\nDue to these ambiguities/restrictions, indexing with a `usize` is simply\nforbidden:\n\n```rust\nlet s = \"hello\";\n\n// The following will not compile!\nprintln!(\"The first letter of s is {}\", s[0]);\n```\n\nIt is more clear, however, how `&s[i..j]` should work (that is,\nindexing with a range). It should accept byte indices (to be constant-time)\nand return a `&str` which is UTF-8 encoded. This is also called \"string slicing\".\nNote this will panic if the byte indices provided are not character\nboundaries - see [`is_char_boundary`] for more details. See the implementations\nfor [`SliceIndex<str>`] for more details on string slicing. For a non-panicking\nversion of string slicing, see [`get`].\n\n[`OsString`]: ../../std/ffi/struct.OsString.html \"ffi::OsString\"\n[`SliceIndex<str>`]: core::slice::SliceIndex\n[`as_bytes()`]: str::as_bytes\n[`get`]: str::get\n[`is_char_boundary`]: str::is_char_boundary\n\nThe [`bytes`] and [`chars`] methods return iterators over the bytes and\ncodepoints of the string, respectively. To iterate over codepoints along\nwith byte indices, use [`char_indices`].\n\n[`bytes`]: str::bytes\n[`chars`]: str::chars\n[`char_indices`]: str::char_indices\n\n# Deref\n\n`String` implements <code>[Deref]<Target = [str]></code>, and so inherits all of [`str`]'s\nmethods. In addition, this means that you can pass a `String` to a\nfunction which takes a [`&str`] by using an ampersand (`&`):\n\n```rust\nfn takes_str(s: &str) { }\n\nlet s = String::from(\"Hello\");\n\ntakes_str(&s);\n```\n\nThis will create a [`&str`] from the `String` and pass it in. This\nconversion is very inexpensive, and so generally, functions will accept\n[`&str`]s as arguments unless they need a `String` for some specific\nreason.\n\nIn certain cases Rust doesn't have enough information to make this\nconversion, known as [`Deref`] coercion. In the following example a string\nslice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function\n`example_func` takes anything that implements the trait. In this case Rust\nwould need to make two implicit conversions, which Rust doesn't have the\nmeans to do. For that reason, the following example will not compile.\n\n```rust\ntrait TraitExample {}\n\nimpl<'a> TraitExample for &'a str {}\n\nfn example_func<A: TraitExample>(example_arg: A) {}\n\nlet example_string = String::from(\"example_string\");\nexample_func(&example_string);\n```\n\nThere are two options that would work instead. The first would be to\nchange the line `example_func(&example_string);` to\n`example_func(example_string.as_str());`, using the method [`as_str()`]\nto explicitly extract the string slice containing the string. The second\nway changes `example_func(&example_string);` to\n`example_func(&*example_string);`. In this case we are dereferencing a\n`String` to a [`str`], then referencing the [`str`] back to\n[`&str`]. The second way is more idiomatic, however both work to do the\nconversion explicitly rather than relying on the implicit conversion.\n\n# Representation\n\nA `String` is made up of three components: a pointer to some bytes, a\nlength, and a capacity. The pointer points to an internal buffer `String`\nuses to store its data. The length is the number of bytes currently stored\nin the buffer, and the capacity is the size of the buffer in bytes. As such,\nthe length will always be less than or equal to the capacity.\n\nThis buffer is always stored on the heap.\n\nYou can look at these with the [`as_ptr`], [`len`], and [`capacity`]\nmethods:\n\n```rust\nuse std::mem;\n\nlet story = String::from(\"Once upon a time...\");\n\n// Prevent automatically dropping the String's data\nlet mut story = mem::ManuallyDrop::new(story);\n\nlet ptr = story.as_mut_ptr();\nlet len = story.len();\nlet capacity = story.capacity();\n\n// story has nineteen bytes\nassert_eq!(19, len);\n\n// We can re-build a String out of ptr, len, and capacity. This is all\n// unsafe because we are responsible for making sure the components are\n// valid:\nlet s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;\n\nassert_eq!(String::from(\"Once upon a time...\"), s);\n```\n\n[`as_ptr`]: str::as_ptr\n[`len`]: String::len\n[`capacity`]: String::capacity\n\nIf a `String` has enough capacity, adding elements to it will not\nre-allocate. For example, consider this program:\n\n```rust\nlet mut s = String::new();\n\nprintln!(\"{}\", s.capacity());\n\nfor _ in 0..5 {\n s.push_str(\"hello\");\n println!(\"{}\", s.capacity());\n}\n```\n\nThis will output the following:\n\n```text\n0\n5\n10\n20\n20\n40\n```\n\nAt first, we have no memory allocated at all, but as we append to the\nstring, it increases its capacity appropriately. If we instead use the\n[`with_capacity`] method to allocate the correct capacity initially:\n\n```rust\nlet mut s = String::with_capacity(25);\n\nprintln!(\"{}\", s.capacity());\n\nfor _ in 0..5 {\n s.push_str(\"hello\");\n println!(\"{}\", s.capacity());\n}\n```\n\n[`with_capacity`]: String::with_capacity\n\nWe end up with a different output:\n\n```text\n25\n25\n25\n25\n25\n25\n```\n\nHere, there's no need to allocate more memory inside the loop.\n\n[str]: prim@str \"str\"\n[`str`]: prim@str \"str\"\n[`&str`]: prim@str \"&str\"\n[Deref]: core::ops::Deref \"ops::Deref\"\n[`Deref`]: core::ops::Deref \"ops::Deref\"\n[`as_str()`]: String::as_str" }, filterText = "String", kind = 22, label = "String", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "String", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Trait for equality comparisons which are [equivalence relations](\nhttps://en.wikipedia.org/wiki/Equivalence_relation).\n\nThis means, that in addition to `a == b` and `a != b` being strict inverses, the equality must\nbe (for all `a`, `b` and `c`):\n\n- reflexive: `a == a`;\n- symmetric: `a == b` implies `b == a`; and\n- transitive: `a == b` and `b == c` implies `a == c`.\n\nThis property cannot be checked by the compiler, and therefore `Eq` implies\n[`PartialEq`], and has no extra methods.\n\n## Derivable\n\nThis trait can be used with `#[derive]`. When `derive`d, because `Eq` has\nno extra methods, it is only informing the compiler that this is an\nequivalence relation rather than a partial equivalence relation. Note that\nthe `derive` strategy requires all fields are `Eq`, which isn't\nalways desired.\n\n## How can I implement `Eq`?\n\nIf you cannot use the `derive` strategy, specify that your type implements\n`Eq`, which has no methods:\n\n```rust\nenum BookFormat { Paperback, Hardback, Ebook }\nstruct Book {\n isbn: i32,\n format: BookFormat,\n}\nimpl PartialEq for Book {\n fn eq(&self, other: &Self) -> bool {\n self.isbn == other.isbn\n }\n}\nimpl Eq for Book {}\n```" }, filterText = "Eq", kind = 8, label = "Eq", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Eq", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "A value-to-value conversion that consumes the input value. The\nopposite of [`From`].\n\nOne should avoid implementing [`Into`] and implement [`From`] instead.\nImplementing [`From`] automatically provides one with an implementation of [`Into`]\nthanks to the blanket implementation in the standard library.\n\nPrefer using [`Into`] over [`From`] when specifying trait bounds on a generic function\nto ensure that types that only implement [`Into`] can be used as well.\n\n**Note: This trait must not fail**. If the conversion can fail, use [`TryInto`].\n\n# Generic Implementations\n\n- [`From`]`<T> for U` implies `Into<U> for T`\n- [`Into`] is reflexive, which means that `Into<T> for T` is implemented\n\n# Implementing [`Into`] for conversions to external types in old versions of Rust\n\nPrior to Rust 1.41, if the destination type was not part of the current crate\nthen you couldn't implement [`From`] directly.\nFor example, take this code:\n\n```rust\nstruct Wrapper<T>(Vec<T>);\nimpl<T> From<Wrapper<T>> for Vec<T> {\n fn from(w: Wrapper<T>) -> Vec<T> {\n w.0\n }\n}\n```\nThis will fail to compile in older versions of the language because Rust's orphaning rules\nused to be a little bit more strict. To bypass this, you could implement [`Into`] directly:\n\n```rust\nstruct Wrapper<T>(Vec<T>);\nimpl<T> Into<Vec<T>> for Wrapper<T> {\n fn into(self) -> Vec<T> {\n self.0\n }\n}\n```\n\nIt is important to understand that [`Into`] does not provide a [`From`] implementation\n(as [`From`] does with [`Into`]). Therefore, you should always try to implement [`From`]\nand then fall back to [`Into`] if [`From`] can't be implemented.\n\n# Examples\n\n[`String`] implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>`:\n\nIn order to express that we want a generic function to take all arguments that can be\nconverted to a specified type `T`, we can use a trait bound of [`Into`]`<T>`.\nFor example: The function `is_hello` takes all arguments that can be converted into a\n[`Vec`]`<`[`u8`]`>`.\n\n```rust\nfn is_hello<T: Into<Vec<u8>>>(s: T) {\n let bytes = b\"hello\".to_vec();\n assert_eq!(bytes, s.into());\n}\n\nlet s = \"hello\".to_string();\nis_hello(s);\n```\n\n[`String`]: ../../std/string/struct.String.html\n[`Vec`]: ../../std/vec/struct.Vec.html" }, filterText = "Into", kind = 8, label = "Into", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Into", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "A common trait for the ability to explicitly duplicate an object.\n\nDiffers from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while\n`Clone` is always explicit and may or may not be expensive. In order to enforce\nthese characteristics, Rust does not allow you to reimplement [`Copy`], but you\nmay reimplement `Clone` and run arbitrary code.\n\nSince `Clone` is more general than [`Copy`], you can automatically make anything\n[`Copy`] be `Clone` as well.\n\n## Derivable\n\nThis trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d\nimplementation of [`Clone`] calls [`clone`] on each field.\n\n[`clone`]: Clone::clone\n\nFor a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on\ngeneric parameters.\n\n```rust\n// `derive` implements Clone for Reading<T> when T is Clone.\n#[derive(Clone)]\nstruct Reading<T> {\n frequency: T,\n}\n```\n\n## How can I implement `Clone`?\n\nTypes that are [`Copy`] should have a trivial implementation of `Clone`. More formally:\nif `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.\nManual implementations should be careful to uphold this invariant; however, unsafe code\nmust not rely on it to ensure memory safety.\n\nAn example is a generic struct holding a function pointer. In this case, the\nimplementation of `Clone` cannot be `derive`d, but can be implemented as:\n\n```rust\nstruct Generate<T>(fn() -> T);\n\nimpl<T> Copy for Generate<T> {}\n\nimpl<T> Clone for Generate<T> {\n fn clone(&self) -> Self {\n *self\n }\n}\n```\n\n## Additional implementors\n\nIn addition to the [implementors listed below][impls],\nthe following types also implement `Clone`:\n\n* Function item types (i.e., the distinct types defined for each function)\n* Function pointer types (e.g., `fn() -> i32`)\n* Tuple types, if each component also implements `Clone` (e.g., `()`, `(i32, bool)`)\n* Closure types, if they capture no value from the environment\n or if all such captured values implement `Clone` themselves.\n Note that variables captured by shared reference always implement `Clone`\n (even if the referent doesn't),\n while variables captured by mutable reference never implement `Clone`.\n\n[impls]: #implementors" }, filterText = "Clone", kind = 8, label = "Clone", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Clone", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, command = { command = "editor.action.triggerParameterHints", title = "triggerParameterHints" }, deprecated = false, documentation = { kind = "markdown", value = "`Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).\n\nSee the [module documentation](self) for details." }, filterText = "Result", insertTextFormat = 2, kind = 13, label = "Result<…>", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Result<$0>", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "An attempted conversion that consumes `self`, which may or may not be\nexpensive.\n\nLibrary authors should usually not directly implement this trait,\nbut should prefer implementing the [`TryFrom`] trait, which offers\ngreater flexibility and provides an equivalent `TryInto`\nimplementation for free, thanks to a blanket implementation in the\nstandard library. For more information on this, see the\ndocumentation for [`Into`].\n\n# Implementing `TryInto`\n\nThis suffers the same restrictions and reasoning as implementing\n[`Into`], see there for details." }, filterText = "TryInto", kind = 8, label = "TryInto", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "TryInto", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, command = { command = "editor.action.triggerParameterHints", title = "triggerParameterHints" }, deprecated = false, documentation = { kind = "markdown", value = "A pointer type for heap allocation.\n\nSee the [module-level documentation](../../std/boxed/index.html) for more." }, filterText = "Box", insertTextFormat = 2, kind = 22, label = "Box<…>", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Box<$0>", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Conversion from an [`Iterator`].\n\nBy implementing `FromIterator` for a type, you define how it will be\ncreated from an iterator. This is common for types which describe a\ncollection of some kind.\n\nIf you want to create a collection from the contents of an iterator, the\n[`Iterator::collect()`] method is preferred. However, when you need to\nspecify the container type, [`FromIterator::from_iter()`] can be more\nreadable than using a turbofish (e.g. `::<Vec<_>>()`). See the\n[`Iterator::collect()`] documentation for more examples of its use.\n\nSee also: [`IntoIterator`].\n\n# Examples\n\nBasic usage:\n\n```rust\nlet five_fives = std::iter::repeat(5).take(5);\n\nlet v = Vec::from_iter(five_fives);\n\nassert_eq!(v, vec![5, 5, 5, 5, 5]);\n```\n\nUsing [`Iterator::collect()`] to implicitly use `FromIterator`:\n\n```rust\nlet five_fives = std::iter::repeat(5).take(5);\n\nlet v: Vec<i32> = five_fives.collect();\n\nassert_eq!(v, vec![5, 5, 5, 5, 5]);\n```\n\nUsing [`FromIterator::from_iter()`] as a more readable alternative to\n[`Iterator::collect()`]:\n\n```rust\nuse std::collections::VecDeque;\nlet first = (0..10).collect::<VecDeque<i32>>();\nlet second = VecDeque::from_iter(0..10);\n\nassert_eq!(first, second);\n```\n\nImplementing `FromIterator` for your type:\n\n```rust\n// A sample collection, that's just a wrapper over Vec<T>\n#[derive(Debug)]\nstruct MyCollection(Vec<i32>);\n\n// Let's give it some methods so we can create one and add things\n// to it.\nimpl MyCollection {\n fn new() -> MyCollection {\n MyCollection(Vec::new())\n }\n\n fn add(&mut self, elem: i32) {\n self.0.push(elem);\n }\n}\n\n// and we'll implement FromIterator\nimpl FromIterator<i32> for MyCollection {\n fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {\n let mut c = MyCollection::new();\n\n for i in iter {\n c.add(i);\n }\n\n c\n }\n}\n\n// Now we can make a new iterator...\nlet iter = (0..5).into_iter();\n\n// ... and make a MyCollection out of it\nlet c = MyCollection::from_iter(iter);\n\nassert_eq!(c.0, vec![0, 1, 2, 3, 4]);\n\n// collect works too!\n\nlet iter = (0..5).into_iter();\nlet c: MyCollection = iter.collect();\n\nassert_eq!(c.0, vec![0, 1, 2, 3, 4]);\n```" }, filterText = "FromIterator", kind = 8, label = "FromIterator", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "FromIterator", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "An iterator that knows its exact length.\n\nMany [`Iterator`]s don't know how many times they will iterate, but some do.\nIf an iterator knows how many times it can iterate, providing access to\nthat information can be useful. For example, if you want to iterate\nbackwards, a good start is to know where the end is.\n\nWhen implementing an `ExactSizeIterator`, you must also implement\n[`Iterator`]. When doing so, the implementation of [`Iterator::size_hint`]\n*must* return the exact size of the iterator.\n\nThe [`len`] method has a default implementation, so you usually shouldn't\nimplement it. However, you may be able to provide a more performant\nimplementation than the default, so overriding it in this case makes sense.\n\nNote that this trait is a safe trait and as such does *not* and *cannot*\nguarantee that the returned length is correct. This means that `unsafe`\ncode **must not** rely on the correctness of [`Iterator::size_hint`]. The\nunstable and unsafe [`TrustedLen`](super::marker::TrustedLen) trait gives\nthis additional guarantee.\n\n[`len`]: ExactSizeIterator::len\n\n# Examples\n\nBasic usage:\n\n```rust\n// a finite range knows exactly how many times it will iterate\nlet five = 0..5;\n\nassert_eq!(5, five.len());\n```\n\nIn the [module-level docs], we implemented an [`Iterator`], `Counter`.\nLet's implement `ExactSizeIterator` for it as well:\n\n[module-level docs]: crate::iter\n\n```rust\nimpl ExactSizeIterator for Counter {\n // We can easily calculate the remaining number of iterations.\n fn len(&self) -> usize {\n 5 - self.count\n }\n}\n\n// And now we can use it!\n\nlet counter = Counter::new();\n\nassert_eq!(5, counter.len());\n```" }, filterText = "ExactSizeIterator", kind = 8, label = "ExactSizeIterator", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "ExactSizeIterator", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = 'Used to do a cheap reference-to-reference conversion.\n\nThis trait is similar to [`AsMut`] which is used for converting between mutable references.\nIf you need to do a costly conversion it is better to implement [`From`] with type\n`&T` or write a custom function.\n\n`AsRef` has the same signature as [`Borrow`], but [`Borrow`] is different in a few aspects:\n\n- Unlike `AsRef`, [`Borrow`] has a blanket impl for any `T`, and can be used to accept either\n a reference or a value.\n- [`Borrow`] also requires that [`Hash`], [`Eq`] and [`Ord`] for a borrowed value are\n equivalent to those of the owned value. For this reason, if you want to\n borrow only a single field of a struct you can implement `AsRef`, but not [`Borrow`].\n\n**Note: This trait must not fail**. If the conversion can fail, use a\ndedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].\n\n# Generic Implementations\n\n- `AsRef` auto-dereferences if the inner type is a reference or a mutable\n reference (e.g.: `foo.as_ref()` will work the same if `foo` has type\n `&mut Foo` or `&&mut Foo`)\n\n# Examples\n\nBy using trait bounds we can accept arguments of different types as long as they can be\nconverted to the specified type `T`.\n\nFor example: By creating a generic function that takes an `AsRef<str>` we express that we\nwant to accept all references that can be converted to [`&str`] as an argument.\nSince both [`String`] and [`&str`] implement `AsRef<str>` we can accept both as input argument.\n\n[`&str`]: primitive@str\n[`Borrow`]: crate::borrow::Borrow\n[`Eq`]: crate::cmp::Eq\n[`Ord`]: crate::cmp::Ord\n[`String`]: ../../std/string/struct.String.html\n\n```rust\nfn is_hello<T: AsRef<str>>(s: T) {\n assert_eq!("hello", s.as_ref());\n}\n\nlet s = "hello";\nis_hello(s);\n\nlet s = "hello".to_string();\nis_hello(s);\n```' }, filterText = "AsRef", kind = 8, label = "AsRef", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "AsRef", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "An interface for dealing with iterators.\n\nThis is the main iterator trait. For more about the concept of iterators\ngenerally, please see the [module-level documentation]. In particular, you\nmay want to know how to [implement `Iterator`][impl].\n\n[module-level documentation]: crate::iter\n[impl]: crate::iter#implementing-iterator" }, filterText = "Iterator", kind = 8, label = "Iterator", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Iterator", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).\n\nImplementations must be consistent with the [`PartialOrd`] implementation, and ensure\n`max`, `min`, and `clamp` are consistent with `cmp`:\n\n- `partial_cmp(a, b) == Some(cmp(a, b))`.\n- `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).\n- `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).\n- For `a.clamp(min, max)`, see the [method docs](#method.clamp)\n (ensured by the default implementation).\n\nIt's easy to accidentally make `cmp` and `partial_cmp` disagree by\nderiving some of the traits and manually implementing others.\n\n## Corollaries\n\nFrom the above and the requirements of `PartialOrd`, it follows that `<` defines a strict total order.\nThis means that for all `a`, `b` and `c`:\n\n- exactly one of `a < b`, `a == b` or `a > b` is true; and\n- `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.\n\n## Derivable\n\nThis trait can be used with `#[derive]`.\n\nWhen `derive`d on structs, it will produce a\n[lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering\nbased on the top-to-bottom declaration order of the struct's members.\n\nWhen `derive`d on enums, variants are ordered by their discriminants.\nBy default, the discriminant is smallest for variants at the top, and\nlargest for variants at the bottom. Here's an example:\n\n```rust\n#[derive(PartialEq, Eq, PartialOrd, Ord)]\nenum E {\n Top,\n Bottom,\n}\n\nassert!(E::Top < E::Bottom);\n```\n\nHowever, manually setting the discriminants can override this default\nbehavior:\n\n```rust\n#[derive(PartialEq, Eq, PartialOrd, Ord)]\nenum E {\n Top = 2,\n Bottom = 1,\n}\n\nassert!(E::Bottom < E::Top);\n```\n\n## Lexicographical comparison\n\nLexicographical comparison is an operation with the following properties:\n - Two sequences are compared element by element.\n - The first mismatching element defines which sequence is lexicographically less or greater than the other.\n - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.\n - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.\n - An empty sequence is lexicographically less than any non-empty sequence.\n - Two empty sequences are lexicographically equal.\n\n## How can I implement `Ord`?\n\n`Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).\n\nThen you must define an implementation for [`cmp`]. You may find it useful to use\n[`cmp`] on your type's fields.\n\nHere's an example where you want to sort people by height only, disregarding `id`\nand `name`:\n\n```rust\nuse std::cmp::Ordering;\n\n#[derive(Eq)]\nstruct Person {\n id: u32,\n name: String,\n height: u32,\n}\n\nimpl Ord for Person {\n fn cmp(&self, other: &Self) -> Ordering {\n self.height.cmp(&other.height)\n }\n}\n\nimpl PartialOrd for Person {\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n Some(self.cmp(other))\n }\n}\n\nimpl PartialEq for Person {\n fn eq(&self, other: &Self) -> bool {\n self.height == other.height\n }\n}\n```\n\n[`cmp`]: Ord::cmp" }, filterText = "Ord", kind = 8, label = "Ord", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Ord", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "A generalization of `Clone` to borrowed data.\n\nSome types make it possible to go from borrowed to owned, usually by\nimplementing the `Clone` trait. But `Clone` works only for going from `&T`\nto `T`. The `ToOwned` trait generalizes `Clone` to construct owned data\nfrom any borrow of a given type." }, filterText = "ToOwned", kind = 8, label = "ToOwned", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "ToOwned", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, command = { command = "editor.action.triggerParameterHints", title = "triggerParameterHints" }, deprecated = false, documentation = { kind = "markdown", value = "A contiguous growable array type, written as `Vec<T>`, short for 'vector'.\n\n# Examples\n\n```rust\nlet mut vec = Vec::new();\nvec.push(1);\nvec.push(2);\n\nassert_eq!(vec.len(), 2);\nassert_eq!(vec[0], 1);\n\nassert_eq!(vec.pop(), Some(2));\nassert_eq!(vec.len(), 1);\n\nvec[0] = 7;\nassert_eq!(vec[0], 7);\n\nvec.extend([1, 2, 3].iter().copied());\n\nfor x in &vec {\n println!(\"{x}\");\n}\nassert_eq!(vec, [7, 1, 2, 3]);\n```\n\nThe [`vec!`] macro is provided for convenient initialization:\n\n```rust\nlet mut vec1 = vec![1, 2, 3];\nvec1.push(4);\nlet vec2 = Vec::from([1, 2, 3, 4]);\nassert_eq!(vec1, vec2);\n```\n\nIt can also initialize each element of a `Vec<T>` with a given value.\nThis may be more efficient than performing allocation and initialization\nin separate steps, especially when initializing a vector of zeros:\n\n```rust\nlet vec = vec![0; 5];\nassert_eq!(vec, [0, 0, 0, 0, 0]);\n\n// The following is equivalent, but potentially slower:\nlet mut vec = Vec::with_capacity(5);\nvec.resize(5, 0);\nassert_eq!(vec, [0, 0, 0, 0, 0]);\n```\n\nFor more information, see\n[Capacity and Reallocation](#capacity-and-reallocation).\n\nUse a `Vec<T>` as an efficient stack:\n\n```rust\nlet mut stack = Vec::new();\n\nstack.push(1);\nstack.push(2);\nstack.push(3);\n\nwhile let Some(top) = stack.pop() {\n // Prints 3, 2, 1\n println!(\"{top}\");\n}\n```\n\n# Indexing\n\nThe `Vec` type allows to access values by index, because it implements the\n[`Index`] trait. An example will be more explicit:\n\n```rust\nlet v = vec![0, 2, 4, 6];\nprintln!(\"{}\", v[1]); // it will display '2'\n```\n\nHowever be careful: if you try to access an index which isn't in the `Vec`,\nyour software will panic! You cannot do this:\n\n```rust\nlet v = vec![0, 2, 4, 6];\nprintln!(\"{}\", v[6]); // it will panic!\n```\n\nUse [`get`] and [`get_mut`] if you want to check whether the index is in\nthe `Vec`.\n\n# Slicing\n\nA `Vec` can be mutable. On the other hand, slices are read-only objects.\nTo get a [slice][prim@slice], use [`&`]. Example:\n\n```rust\nfn read_slice(slice: &[usize]) {\n // ...\n}\n\nlet v = vec![0, 1];\nread_slice(&v);\n\n// ... and that's all!\n// you can also do it like this:\nlet u: &[usize] = &v;\n// or like this:\nlet u: &[_] = &v;\n```\n\nIn Rust, it's more common to pass slices as arguments rather than vectors\nwhen you just want to provide read access. The same goes for [`String`] and\n[`&str`].\n\n# Capacity and reallocation\n\nThe capacity of a vector is the amount of space allocated for any future\nelements that will be added onto the vector. This is not to be confused with\nthe *length* of a vector, which specifies the number of actual elements\nwithin the vector. If a vector's length exceeds its capacity, its capacity\nwill automatically be increased, but its elements will have to be\nreallocated.\n\nFor example, a vector with capacity 10 and length 0 would be an empty vector\nwith space for 10 more elements. Pushing 10 or fewer elements onto the\nvector will not change its capacity or cause reallocation to occur. However,\nif the vector's length is increased to 11, it will have to reallocate, which\ncan be slow. For this reason, it is recommended to use [`Vec::with_capacity`]\nwhenever possible to specify how big the vector is expected to get.\n\n# Guarantees\n\nDue to its incredibly fundamental nature, `Vec` makes a lot of guarantees\nabout its design. This ensures that it's as low-overhead as possible in\nthe general case, and can be correctly manipulated in primitive ways\nby unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.\nIf additional type parameters are added (e.g., to support custom allocators),\noverriding their defaults may change the behavior.\n\nMost fundamentally, `Vec` is and always will be a (pointer, capacity, length)\ntriplet. No more, no less. The order of these fields is completely\nunspecified, and you should use the appropriate methods to modify these.\nThe pointer will never be null, so this type is null-pointer-optimized.\n\nHowever, the pointer might not actually point to allocated memory. In particular,\nif you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],\n[`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]\non an empty Vec, it will not allocate memory. Similarly, if you store zero-sized\ntypes inside a `Vec`, it will not allocate space for them. *Note that in this case\nthe `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only\nif <code>[mem::size_of::\\<T>]\\() * [capacity]\\() > 0</code>. In general, `Vec`'s allocation\ndetails are very subtle --- if you intend to allocate memory using a `Vec`\nand use it for something else (either to pass to unsafe code, or to build your\nown memory-backed collection), be sure to deallocate this memory by using\n`from_raw_parts` to recover the `Vec` and then dropping it.\n\nIf a `Vec` *has* allocated memory, then the memory it points to is on the heap\n(as defined by the allocator Rust is configured to use by default), and its\npointer points to [`len`] initialized, contiguous elements in order (what\nyou would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>\nlogically uninitialized, contiguous elements.\n\nA vector containing the elements `'a'` and `'b'` with capacity 4 can be\nvisualized as below. The top part is the `Vec` struct, it contains a\npointer to the head of the allocation in the heap, length and capacity.\nThe bottom part is the allocation on the heap, a contiguous memory block.\n\n```text\n ptr len capacity\n +--------+--------+--------+\n | 0x0123 | 2 | 4 |\n +--------+--------+--------+\n |\n v\nHeap +--------+--------+--------+--------+\n | 'a' | 'b' | uninit | uninit |\n +--------+--------+--------+--------+\n```\n\n- **uninit** represents memory that is not initialized, see [`MaybeUninit`].\n- Note: the ABI is not stable and `Vec` makes no guarantees about its memory\n layout (including the order of fields).\n\n`Vec` will never perform a \"small optimization\" where elements are actually\nstored on the stack for two reasons:\n\n* It would make it more difficult for unsafe code to correctly manipulate\n a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were\n only moved, and it would be more difficult to determine if a `Vec` had\n actually allocated memory.\n\n* It would penalize the general case, incurring an additional branch\n on every access.\n\n`Vec` will never automatically shrink itself, even if completely empty. This\nensures no unnecessary allocations or deallocations occur. Emptying a `Vec`\nand then filling it back up to the same [`len`] should incur no calls to\nthe allocator. If you wish to free up unused memory, use\n[`shrink_to_fit`] or [`shrink_to`].\n\n[`push`] and [`insert`] will never (re)allocate if the reported capacity is\nsufficient. [`push`] and [`insert`] *will* (re)allocate if\n<code>[len] == [capacity]</code>. That is, the reported capacity is completely\naccurate, and can be relied on. It can even be used to manually free the memory\nallocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even\nwhen not necessary.\n\n`Vec` does not guarantee any particular growth strategy when reallocating\nwhen full, nor when [`reserve`] is called. The current strategy is basic\nand it may prove desirable to use a non-constant growth factor. Whatever\nstrategy is used will of course guarantee *O*(1) amortized [`push`].\n\n`vec![x; n]`, `vec![a, b, c, d]`, and\n[`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`\nwith exactly the requested capacity. If <code>[len] == [capacity]</code>,\n(as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to\nand from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.\n\n`Vec` will not specifically overwrite any data that is removed from it,\nbut also won't specifically preserve it. Its uninitialized memory is\nscratch space that it may use however it wants. It will generally just do\nwhatever is most efficient or otherwise easy to implement. Do not rely on\nremoved data to be erased for security purposes. Even if you drop a `Vec`, its\nbuffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory\nfirst, that might not actually happen because the optimizer does not consider\nthis a side-effect that must be preserved. There is one case which we will\nnot break, however: using `unsafe` code to write to the excess capacity,\nand then increasing the length to match, is always valid.\n\nCurrently, `Vec` does not guarantee the order in which elements are dropped.\nThe order has changed in the past and may change again.\n\n[`get`]: ../../std/vec/struct.Vec.html#method.get\n[`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut\n[`String`]: crate::string::String\n[`&str`]: type@str\n[`shrink_to_fit`]: Vec::shrink_to_fit\n[`shrink_to`]: Vec::shrink_to\n[capacity]: Vec::capacity\n[`capacity`]: Vec::capacity\n[mem::size_of::\\<T>]: core::mem::size_of\n[len]: Vec::len\n[`len`]: Vec::len\n[`push`]: Vec::push\n[`insert`]: Vec::insert\n[`reserve`]: Vec::reserve\n[`MaybeUninit`]: core::mem::MaybeUninit\n[owned slice]: Box" }, filterText = "Vec", insertTextFormat = 2, kind = 22, label = "Vec<…>", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Vec<$0>", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "The version of the call operator that takes an immutable receiver.\n\nInstances of `Fn` can be called repeatedly without mutating state.\n\n*This trait (`Fn`) is not to be confused with [function pointers]\n(`fn`).*\n\n`Fn` is implemented automatically by closures which only take immutable\nreferences to captured variables or don't capture anything at all, as well\nas (safe) [function pointers] (with some caveats, see their documentation\nfor more details). Additionally, for any type `F` that implements `Fn`, `&F`\nimplements `Fn`, too.\n\nSince both [`FnMut`] and [`FnOnce`] are supertraits of `Fn`, any\ninstance of `Fn` can be used as a parameter where a [`FnMut`] or [`FnOnce`]\nis expected.\n\nUse `Fn` as a bound when you want to accept a parameter of function-like\ntype and need to call it repeatedly and without mutating state (e.g., when\ncalling it concurrently). If you do not need such strict requirements, use\n[`FnMut`] or [`FnOnce`] as bounds.\n\nSee the [chapter on closures in *The Rust Programming Language*][book] for\nsome more information on this topic.\n\nAlso of note is the special syntax for `Fn` traits (e.g.\n`Fn(usize, bool) -> usize`). Those interested in the technical details of\nthis can refer to [the relevant section in the *Rustonomicon*][nomicon].\n\n[book]: ../../book/ch13-01-closures.html\n[function pointers]: fn\n[nomicon]: ../../nomicon/hrtb.html\n\n# Examples\n\n## Calling a closure\n\n```rust\nlet square = |x| x * x;\nassert_eq!(square(5), 25);\n```\n\n## Using a `Fn` parameter\n\n```rust\nfn call_with_one<F>(func: F) -> usize\n where F: Fn(usize) -> usize {\n func(1)\n}\n\nlet double = |x| x * 2;\nassert_eq!(call_with_one(double), 2);\n```" }, filterText = "Fn", kind = 8, label = "Fn", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Fn", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Conversion into an [`Iterator`].\n\nBy implementing `IntoIterator` for a type, you define how it will be\nconverted to an iterator. This is common for types which describe a\ncollection of some kind.\n\nOne benefit of implementing `IntoIterator` is that your type will [work\nwith Rust's `for` loop syntax](crate::iter#for-loops-and-intoiterator).\n\nSee also: [`FromIterator`].\n\n# Examples\n\nBasic usage:\n\n```rust\nlet v = [1, 2, 3];\nlet mut iter = v.into_iter();\n\nassert_eq!(Some(1), iter.next());\nassert_eq!(Some(2), iter.next());\nassert_eq!(Some(3), iter.next());\nassert_eq!(None, iter.next());\n```\nImplementing `IntoIterator` for your type:\n\n```rust\n// A sample collection, that's just a wrapper over Vec<T>\n#[derive(Debug)]\nstruct MyCollection(Vec<i32>);\n\n// Let's give it some methods so we can create one and add things\n// to it.\nimpl MyCollection {\n fn new() -> MyCollection {\n MyCollection(Vec::new())\n }\n\n fn add(&mut self, elem: i32) {\n self.0.push(elem);\n }\n}\n\n// and we'll implement IntoIterator\nimpl IntoIterator for MyCollection {\n type Item = i32;\n type IntoIter = std::vec::IntoIter<Self::Item>;\n\n fn into_iter(self) -> Self::IntoIter {\n self.0.into_iter()\n }\n}\n\n// Now we can make a new collection...\nlet mut c = MyCollection::new();\n\n// ... add some stuff to it ...\nc.add(0);\nc.add(1);\nc.add(2);\n\n// ... and then turn it into an Iterator:\nfor (i, n) in c.into_iter().enumerate() {\n assert_eq!(i as i32, n);\n}\n```\n\nIt is common to use `IntoIterator` as a trait bound. This allows\nthe input collection type to change, so long as it is still an\niterator. Additional bounds can be specified by restricting on\n`Item`:\n\n```rust\nfn collect_as_strings<T>(collection: T) -> Vec<String>\nwhere\n T: IntoIterator,\n T::Item: std::fmt::Debug,\n{\n collection\n .into_iter()\n .map(|item| format!(\"{item:?}\"))\n .collect()\n}\n```" }, filterText = "IntoIterator", kind = 8, label = "IntoIterator", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "IntoIterator", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "A trait for giving a type a useful default value.\n\nSometimes, you want to fall back to some kind of default value, and\ndon't particularly care what it is. This comes up often with `struct`s\nthat define a set of options:\n\n```rust\nstruct SomeOptions {\n foo: i32,\n bar: f32,\n}\n```\n\nHow can we define some default values? You can use `Default`:\n\n```rust\n#[derive(Default)]\nstruct SomeOptions {\n foo: i32,\n bar: f32,\n}\n\nfn main() {\n let options: SomeOptions = Default::default();\n}\n```\n\nNow, you get all of the default values. Rust implements `Default` for various primitives types.\n\nIf you want to override a particular option, but still retain the other defaults:\n\n```rust\nfn main() {\n let options = SomeOptions { foo: 42, ..Default::default() };\n}\n```\n\n## Derivable\n\nThis trait can be used with `#[derive]` if all of the type's fields implement\n`Default`. When `derive`d, it will use the default value for each field's type.\n\n### `enum`s\n\nWhen using `#[derive(Default)]` on an `enum`, you need to choose which unit variant will be\ndefault. You do this by placing the `#[default]` attribute on the variant.\n\n```rust\n#[derive(Default)]\nenum Kind {\n #[default]\n A,\n B,\n C,\n}\n```\n\nYou cannot use the `#[default]` attribute on non-unit or non-exhaustive variants.\n\n## How can I implement `Default`?\n\nProvide an implementation for the `default()` method that returns the value of\nyour type that should be the default:\n\n```rust\nenum Kind {\n A,\n B,\n C,\n}\n\nimpl Default for Kind {\n fn default() -> Self { Kind::A }\n}\n```\n\n# Examples\n\n```rust\n#[derive(Default)]\nstruct SomeOptions {\n foo: i32,\n bar: f32,\n}\n```" }, filterText = "Default", kind = 8, label = "Default", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Default", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Types with a constant size known at compile time.\n\nAll type parameters have an implicit bound of `Sized`. The special syntax\n`?Sized` can be used to remove this bound if it's not appropriate.\n\n```rust\nstruct Foo<T>(T);\nstruct Bar<T: ?Sized>(T);\n\n// struct FooUse(Foo<[i32]>); // error: Sized is not implemented for [i32]\nstruct BarUse(Bar<[i32]>); // OK\n```\n\nThe one exception is the implicit `Self` type of a trait. A trait does not\nhave an implicit `Sized` bound as this is incompatible with [trait object]s\nwhere, by definition, the trait needs to work with all possible implementors,\nand thus could be any size.\n\nAlthough Rust will let you bind `Sized` to a trait, you won't\nbe able to use it to form a trait object later:\n\n```rust\ntrait Foo { }\ntrait Bar: Sized { }\n\nstruct Impl;\nimpl Foo for Impl { }\nimpl Bar for Impl { }\n\nlet x: &dyn Foo = &Impl; // OK\n// let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot\n // be made into an object\n```\n\n[trait object]: ../../book/ch17-02-trait-objects.html" }, filterText = "Sized", kind = 8, label = "Sized", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Sized", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Types for which it is safe to share references between threads.\n\nThis trait is automatically implemented when the compiler determines\nit's appropriate.\n\nThe precise definition is: a type `T` is [`Sync`] if and only if `&T` is\n[`Send`]. In other words, if there is no possibility of\n[undefined behavior][ub] (including data races) when passing\n`&T` references between threads.\n\nAs one would expect, primitive types like [`u8`] and [`f64`]\nare all [`Sync`], and so are simple aggregate types containing them,\nlike tuples, structs and enums. More examples of basic [`Sync`]\ntypes include \"immutable\" types like `&T`, and those with simple\ninherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and\nmost other collection types. (Generic parameters need to be [`Sync`]\nfor their container to be [`Sync`].)\n\nA somewhat surprising consequence of the definition is that `&mut T`\nis `Sync` (if `T` is `Sync`) even though it seems like that might\nprovide unsynchronized mutation. The trick is that a mutable\nreference behind a shared reference (that is, `& &mut T`)\nbecomes read-only, as if it were a `& &T`. Hence there is no risk\nof a data race.\n\nTypes that are not `Sync` are those that have \"interior\nmutability\" in a non-thread-safe form, such as [`Cell`][cell]\nand [`RefCell`][refcell]. These types allow for mutation of\ntheir contents even through an immutable, shared reference. For\nexample the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires\nonly a shared reference [`&Cell<T>`][cell]. The method performs no\nsynchronization, thus [`Cell`][cell] cannot be `Sync`.\n\nAnother example of a non-`Sync` type is the reference-counting\npointer [`Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone\na new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way.\n\nFor cases when one does need thread-safe interior mutability,\nRust provides [atomic data types], as well as explicit locking via\n[`sync::Mutex`][mutex] and [`sync::RwLock`][rwlock]. These types\nensure that any mutation cannot cause data races, hence the types\nare `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe\nanalogue of [`Rc`][rc].\n\nAny types with interior mutability must also use the\n[`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which\ncan be mutated through a shared reference. Failing to doing this is\n[undefined behavior][ub]. For example, [`transmute`][transmute]-ing\nfrom `&T` to `&mut T` is invalid.\n\nSee [the Nomicon][nomicon-send-and-sync] for more details about `Sync`.\n\n[box]: ../../std/boxed/struct.Box.html\n[vec]: ../../std/vec/struct.Vec.html\n[cell]: crate::cell::Cell\n[refcell]: crate::cell::RefCell\n[rc]: ../../std/rc/struct.Rc.html\n[arc]: ../../std/sync/struct.Arc.html\n[atomic data types]: crate::sync::atomic\n[mutex]: ../../std/sync/struct.Mutex.html\n[rwlock]: ../../std/sync/struct.RwLock.html\n[unsafecell]: crate::cell::UnsafeCell\n[ub]: ../../reference/behavior-considered-undefined.html\n[transmute]: crate::mem::transmute\n[nomicon-send-and-sync]: ../../nomicon/send-and-sync.html" }, filterText = "Sync", kind = 8, label = "Sync", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Sync", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "An iterator able to yield elements from both ends.\n\nSomething that implements `DoubleEndedIterator` has one extra capability\nover something that implements [`Iterator`]: the ability to also take\n`Item`s from the back, as well as the front.\n\nIt is important to note that both back and forth work on the same range,\nand do not cross: iteration is over when they meet in the middle.\n\nIn a similar fashion to the [`Iterator`] protocol, once a\n`DoubleEndedIterator` returns [`None`] from a [`next_back()`], calling it\nagain may or may not ever return [`Some`] again. [`next()`] and\n[`next_back()`] are interchangeable for this purpose.\n\n[`next_back()`]: DoubleEndedIterator::next_back\n[`next()`]: Iterator::next\n\n# Examples\n\nBasic usage:\n\n```rust\nlet numbers = vec![1, 2, 3, 4, 5, 6];\n\nlet mut iter = numbers.iter();\n\nassert_eq!(Some(&1), iter.next());\nassert_eq!(Some(&6), iter.next_back());\nassert_eq!(Some(&5), iter.next_back());\nassert_eq!(Some(&2), iter.next());\nassert_eq!(Some(&3), iter.next());\nassert_eq!(Some(&4), iter.next());\nassert_eq!(None, iter.next());\nassert_eq!(None, iter.next_back());\n```" }, filterText = "DoubleEndedIterator", kind = 8, label = "DoubleEndedIterator", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "DoubleEndedIterator", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = 'The version of the call operator that takes a by-value receiver.\n\nInstances of `FnOnce` can be called, but might not be callable multiple\ntimes. Because of this, if the only thing known about a type is that it\nimplements `FnOnce`, it can only be called once.\n\n`FnOnce` is implemented automatically by closures that might consume captured\nvariables, as well as all types that implement [`FnMut`], e.g., (safe)\n[function pointers] (since `FnOnce` is a supertrait of [`FnMut`]).\n\nSince both [`Fn`] and [`FnMut`] are subtraits of `FnOnce`, any instance of\n[`Fn`] or [`FnMut`] can be used where a `FnOnce` is expected.\n\nUse `FnOnce` as a bound when you want to accept a parameter of function-like\ntype and only need to call it once. If you need to call the parameter\nrepeatedly, use [`FnMut`] as a bound; if you also need it to not mutate\nstate, use [`Fn`].\n\nSee the [chapter on closures in *The Rust Programming Language*][book] for\nsome more information on this topic.\n\nAlso of note is the special syntax for `Fn` traits (e.g.\n`Fn(usize, bool) -> usize`). Those interested in the technical details of\nthis can refer to [the relevant section in the *Rustonomicon*][nomicon].\n\n[book]: ../../book/ch13-01-closures.html\n[function pointers]: fn\n[nomicon]: ../../nomicon/hrtb.html\n\n# Examples\n\n## Using a `FnOnce` parameter\n\n```rust\nfn consume_with_relish<F>(func: F)\n where F: FnOnce() -> String\n{\n // `func` consumes its captured variables, so it cannot be run more\n // than once.\n println!("Consumed: {}", func());\n\n println!("Delicious!");\n\n // Attempting to invoke `func()` again will throw a `use of moved\n // value` error for `func`.\n}\n\nlet x = String::from("x");\nlet consume_and_return_x = move || x;\nconsume_with_relish(consume_and_return_x);\n\n// `consume_and_return_x` can no longer be invoked at this point\n```' }, filterText = "FnOnce", kind = 8, label = "FnOnce", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "FnOnce", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } }, { additionalTextEdits = {}, deprecated = false, documentation = { kind = "markdown", value = "Types that can be transferred across thread boundaries.\n\nThis trait is automatically implemented when the compiler determines it's\nappropriate.\n\nAn example of a non-`Send` type is the reference-counting pointer\n[`rc::Rc`][`Rc`]. If two threads attempt to clone [`Rc`]s that point to the same\nreference-counted value, they might try to update the reference count at the\nsame time, which is [undefined behavior][ub] because [`Rc`] doesn't use atomic\noperations. Its cousin [`sync::Arc`][arc] does use atomic operations (incurring\nsome overhead) and thus is `Send`.\n\nSee [the Nomicon](../../nomicon/send-and-sync.html) for more details.\n\n[`Rc`]: ../../std/rc/struct.Rc.html\n[arc]: ../../std/sync/struct.Arc.html\n[ub]: ../../reference/behavior-considered-undefined.html" }, filterText = "Send", kind = 8, label = "Send", preselect = true, sortText = "ffffffef", textEdit = { insert = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } }, newText = "Send", replace = { end = { character = 36, line = 234 }, start = { character = 36, line = 234 } } } } } } }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment