### Basic `example` attribute usage Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/attributes.md Demonstrates the most basic usage of the `example` attribute. ```rust // This should be a very basic example showing the attribute // used in some way. #[example] fn some_meaningful_name() {} ``` -------------------------------- ### `example` attribute with MetaWord syntax Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/attributes.md Shows the `example` attribute using the `MetaWord` syntax. ```rust #[example] fn f() {} ``` -------------------------------- ### Displaying a Rust Code Example Source: https://github.com/rust-lang/reference.git/blob/master/src/introduction.md Examples are shown in syntax-highlighted boxes. Hidden lines can be revealed by clicking an icon. ```rust # // This is a hidden line. fn main() { println!("This is a code example"); } ``` -------------------------------- ### `example` attribute with MetaNameValueStr syntax Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/attributes.md Illustrates the `example` attribute using the `MetaNameValueStr` syntax, where a string value is provided. ```rust #[example = "example"] fn f() {} ``` -------------------------------- ### Tuple Indexing Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/tuple-expr.md Examples demonstrating how to access fields in tuples and tuple structs using numeric indices. ```rust // Indexing a tuple let pair = ("a string", 2); assert_eq!(pair.1, 2); // Indexing a tuple struct # struct Point(f32, f32); let point = Point(1.0, 0.0); assert_eq!(point.0, 1.0); assert_eq!(point.1, 0.0); ``` -------------------------------- ### Basic Path Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/paths.md Illustrates simple paths consisting of identifier segments. ```rust x; x::y::z; ``` -------------------------------- ### `example` attribute with MetaNameValueStr for 'foo' Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/attributes.md Specific usage of the `example` attribute with `MetaNameValueStr` syntax to specify a 'foo' value. ```rust #[example = "example"] fn some_meaningful_name() {} ``` -------------------------------- ### Reserved Prefix Examples Across Editions Source: https://github.com/rust-lang/reference.git/blob/master/src/tokens.md Examples of reserved prefix usage that are accepted in all editions versus those that are rejected starting in the 2021 edition. ```rust macro_rules! lexes {($($_:tt)*) => {}} lexes!{a #foo} lexes!{continue 'foo} lexes!{match "..." {}} lexes!{r#let#foo} // three tokens: r#let # foo lexes!{'prefix #lt} ``` ```rust macro_rules! lexes {($($_:tt)*) => {}} lexes!{a#foo} lexes!{continue'foo} lexes!{match"..." {}} lexes!{'prefix#lt} ``` -------------------------------- ### Basic Inline Assembly Example Source: https://github.com/rust-lang/reference.git/blob/master/src/inline-assembly.md A simple example of using the `asm!` macro, likely for testing or basic operations. ```rust pub fn main() { # #[cfg(target_arch = "x86_64")]{ assert_eq!(fadd(1.0, 1.0), 2.0); # } } ``` -------------------------------- ### Install mdbook Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/tooling/building.md Install the mdbook tool using Cargo, which is necessary for building the Reference. ```sh cargo install --locked mdbook ``` -------------------------------- ### `example` attribute with MetaListNameValueStr syntax Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/attributes.md Demonstrates the `example` attribute using the `MetaListNameValueStr` syntax, allowing for inner key-value pairs. ```rust #[example(inner = "example")] fn f() {} ``` -------------------------------- ### Basic Method Call Example Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/method-call-expr.md Demonstrates a simple method call chain involving parsing a string, unwrapping a Result, and performing a logarithm operation. This example shows how method calls can be chained. ```rust let pi: Result = "3.14".parse(); let log_pi = pi.unwrap_or(1.0).log(2.72); # assert!(1.14 < log_pi && log_pi < 1.15) ``` -------------------------------- ### Install Nightly Rust Toolchain Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/tooling/building.md Ensure you have the nightly Rust toolchain installed, as it's required for running tests. ```sh rustup toolchain install nightly ``` -------------------------------- ### Example: Using Stdcall ABI Source: https://github.com/rust-lang/reference.git/blob/master/src/items/external-blocks.md Illustrates the "stdcall" ABI, typically used by the Win32 API on x86_32 targets. ```rust unsafe extern "stdcall" ``` -------------------------------- ### Mixed-Site Hygiene Example Source: https://github.com/rust-lang/reference.git/blob/master/src/macros-by-example.md Demonstrates mixed-site hygiene where 'x' is from the definition site and 'func' is from the invocation site. ```rust let x = 1; fn func() { unreachable!("this is never called") } macro_rules! check { () => { assert_eq!(x, 1); // Uses `x` from the definition site. func(); // Uses `func` from the invocation site. }; } { let x = 2; fn func() { /* does not panic */ } check!(); } ``` -------------------------------- ### x86_64 Inline Assembly Example Source: https://github.com/rust-lang/reference.git/blob/master/src/inline-assembly.md This example demonstrates using inline assembly on x86_64 to place a string in memory and retrieve its pointer and length. Ensure the target architecture is x86_64 before compilation. ```rust # #[cfg(target_arch = "x86_64")] { let bytes: *const u8; let len: usize; unsafe { core::arch::asm!( "jmp 3f", "2: .ascii \"Hello World!\"", "3: lea {bytes}, [2b+rip]", "mov {len}, 12", bytes = out(reg) bytes, len = out(reg) len ); } let s = unsafe { core::str::from_utf8_unchecked(core::slice::from_raw_parts(bytes, len)) }; assert_eq!(s, "Hello World!"); # } ``` -------------------------------- ### Usage of Simple Paths Source: https://github.com/rust-lang/reference.git/blob/master/src/paths.md Shows examples of simple paths in 'use' items, visibility markers, attributes, and macros. ```rust use std::io::{self, Write}; mod m { #[clippy::cyclomatic_complexity = "0"] pub (in super) fn f1() {} } ``` -------------------------------- ### Basic Call Expressions Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/call-expr.md Examples of calling a standard function and a closure. ```rust # fn add(x: i32, y: i32) -> i32 { 0 } let three: i32 = add(1i32, 2i32); let name: &'static str = (|| "Rust")(); ``` -------------------------------- ### Define a Macro-by-Example Source: https://github.com/rust-lang/reference.git/blob/master/src/macro-ambiguity.md Example of a macro definition using a matcher with simple and complex non-terminals. ```rust macro_rules! i_am_an_mbe { (start $foo:expr $($i:ident),* end) => ($foo) } ``` -------------------------------- ### Basic Rust Literal Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/literal-expr.md Illustrates the basic syntax for string, character, and integer literals in Rust. ```rust "hello"; // string type '5'; // character type 5; // integer type ``` -------------------------------- ### Example of `diagnostic::do_not_recommend` usage Source: https://github.com/rust-lang/reference.git/blob/master/src/attributes/diagnostics.md This example demonstrates a trait implementation where the `#[diagnostic::do_not_recommend]` attribute would be applied to prevent this specific implementation from being suggested in diagnostic messages. The surrounding code defines traits and types related to SQL expression handling. ```rust # pub trait Expression { # type SqlType; # } # # pub trait AsExpression { # type Expression: Expression; # } # # pub struct Text; # pub struct Integer; # # pub struct Bound(T); # pub struct SelectInt; # # impl Expression for SelectInt { # type SqlType = Integer; # } # # impl Expression for Bound { # type SqlType = T; # } # # impl AsExpression for i32 { # type Expression = Bound; # } # # impl AsExpression for &'_ str { # type Expression = Bound; # } # ``` -------------------------------- ### FIRST Set Example 1 Source: https://github.com/rust-lang/reference.git/blob/master/src/macro-ambiguity.md Illustrates the FIRST set calculation for a complex macro pattern, showing the composition of elements. ```text INPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ g ~~~~~~~~ ~~~~~~~ ~ | | | FIRST: { $d:ident } { $e:expr } { h } ``` ```text INPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ ~~~~~~~~~~~~~~~~~~ ~~~~~~~ ~~~ | | | FIRST: { $d:ident } { h, ε } { f } ``` ```text INPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ g ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~ ~~~~~~~~~ ~ | | | | FIRST: { $d:ident, ε } { h, ε, ; } { f } { g } ``` ```text INPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ g ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | FIRST: { $d:ident, h, ;, f } ``` -------------------------------- ### Basic Match Guard Example Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/match-expr.md Demonstrates a simple match guard to process a number less than 10. ```rust let maybe_digit = Some(0); fn process_digit(i: i32) { } fn process_other(i: i32) { } let message = match maybe_digit { Some(x) if x < 10 => process_digit(x), Some(x) => process_other(x), None => panic!(), }; ``` -------------------------------- ### Macro Invocation Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/macros.md Demonstrates various contexts where macros can be invoked, including expressions, patterns, types, and items. ```rust // Used as an expression. let x = vec![1,2,3]; // Used as a statement. println!("Hello!"); // Used in a pattern. macro_rules! pat { ($i:ident) => (Some($i)) } if let pat!(x) = Some(1) { assert_eq!(x, 1); } // Used in a type. macro_rules! Tuple { { $A:ty, $B:ty } => { ($A, $B) }; } type N2 = Tuple!(i32, i32); // Used as an item. # use std::cell::RefCell; thread_local!(static FOO: RefCell = RefCell::new(1)); // Used as an associated item. macro_rules! const_maker { ($t:ty, $v:tt) => { const CONST: $t = $v; }; } trait T { const_maker!{i32, 7} } // Macro calls within macros. macro_rules! example { () => { println!("Macro call in a macro!") }; } // Outer macro `example` is expanded, then inner macro `println` is expanded. example!(); ``` -------------------------------- ### LAST Set Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/macro-ambiguity.md Demonstrates the calculation of LAST sets for various macro patterns, showing how the final elements are determined. ```text LAST(`$d:ident $e:expr`) = { `$e:expr` } ``` ```text LAST(`$( $d:ident $e:expr );*`) = { `$e:expr`, ε } ``` ```text LAST(`$( $d:ident $e:expr );* $(h)*`) = { `$e:expr`, ε, `h` } ``` ```text LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+`) = { `;` } ``` ```text LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+ g`) = { `g` } ``` -------------------------------- ### Async Closure Example Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/closure-expr.md Demonstrates the usage of async closures within a function that accepts an async callback. ```rust async fn takes_async_callback(f: impl AsyncFn(u64)) { f(0).await; f(1).await; } async fn example() { takes_async_callback(async |i| { core::future::ready(i).await; println!("done with {i}."); }).await; } ``` -------------------------------- ### Example: Using AAPCS ABI Source: https://github.com/rust-lang/reference.git/blob/master/src/items/external-blocks.md Illustrates the "aapcs" ABI, the soft-float calling convention for ARM32 targets. ```rust unsafe extern "aapcs" ``` -------------------------------- ### Rust pin! macro usage Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions.md Example demonstrating the usage of the pin! macro, which takes a super operand. ```rust # use core::pin::pin; ``` -------------------------------- ### Rust Tuple Type Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/types/tuple.md Illustrates various tuple types in Rust, from the unit type to multi-element heterogeneous tuples. ```rust () ``` ```rust (i32,) ``` ```rust (f64, f64) ``` ```rust (String, i32) ``` ```rust (i32, String) ``` ```rust (i32, f64, Vec, Option) ``` -------------------------------- ### Example of a Rust shebang Source: https://github.com/rust-lang/reference.git/blob/master/src/shebang.md A shebang line at the start of a file to specify an interpreter. ```rust #!/usr/bin/env rustx fn main() { println!("Hello!"); } ``` -------------------------------- ### Example: Using SysV64 ABI Source: https://github.com/rust-lang/reference.git/blob/master/src/items/external-blocks.md Demonstrates the "sysv64" ABI, used for x86_64 targets on non-Windows systems, aligning with the System V ABI. ```rust unsafe extern "sysv64" ``` -------------------------------- ### Examples of Rust Identifiers Source: https://github.com/rust-lang/reference.git/blob/master/src/identifiers.md Illustrates various valid Rust identifiers, including standard names, those starting with an underscore, raw identifiers, and identifiers using non-ASCII Unicode characters. ```rust foo _identifier r#true Москва 東京 ``` -------------------------------- ### Example: Using the System ABI Source: https://github.com/rust-lang/reference.git/blob/master/src/items/external-blocks.md Demonstrates the use of the "system" ABI, which is generally equivalent to "C" but has specific behavior on Windows x86_32 for non-variadic and variadic functions. ```rust unsafe extern "system" ``` -------------------------------- ### Rust Function Pointer Type Example Source: https://github.com/rust-lang/reference.git/blob/master/src/types/function-pointer.md Demonstrates the declaration and usage of a function pointer type `Binop` and its assignment with a function `add`. ```rust fn add(x: i32, y: i32) -> i32 { x + y } let mut x = add(5,7); type Binop = fn(i32, i32) -> i32; let bo: Binop = add; x = bo(5,7); ``` -------------------------------- ### Grammar for `example` attribute Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/attributes.md Defines the grammar for the `example` attribute, indicating its structure. ```grammar @root ExampleAttribute -> `example` `(` ... `)` ``` -------------------------------- ### Integer Literal Expression Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/literal-expr.md Demonstrates various integer literal formats including suffixes, radix prefixes, and underscore separators. ```rust 123; // type i32 123i32; // type i32 123u32; // type u32 123_u32; // type u32 let a: u64 = 123; // type u64 0xff; // type i32 0xff_u8; // type u8 0o70; // type i32 0o70_i16; // type i16 0b1111_1111_1001_0000; // type i32 0b1111_1111_1001_0000i64; // type i64 0usize; // type usize ``` -------------------------------- ### Unit-Only Enum Example Source: https://github.com/rust-lang/reference.git/blob/master/src/items/enumerations.md An example of a field-less enum that exclusively contains unit variants. ```rust enum Enum { Foo = 3, Bar = 2, Baz = 1, } ``` -------------------------------- ### Basic Rust Hello World Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/examples.md A simple 'Hello, World!' example in Rust. This snippet demonstrates basic output using the `println!` macro. ```rust println!("Hello!"); ``` -------------------------------- ### Example: Using Win64 ABI Source: https://github.com/rust-lang/reference.git/blob/master/src/items/external-blocks.md Shows the "win64" ABI, which is the standard for Windows x64 targets and is equivalent to the "C" ABI on this platform. ```rust unsafe extern "win64" ``` -------------------------------- ### Serve Reference with Custom Rust Source Path Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/tooling/building.md Serve the Reference documentation using mdbook, specifying the SPEC_RUST_ROOT environment variable to point to a local checkout of the Rust source code for test-linking. ```sh SPEC_RUST_ROOT=/path/to/rust mdbook serve --open ``` -------------------------------- ### Build and Open Reference with mdbook Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/tooling/building.md Build the Reference documentation and automatically open it in your default web browser. ```sh mdbook build --open ``` -------------------------------- ### FOLLOW Set Examples for Complex Macros Source: https://github.com/rust-lang/reference.git/blob/master/src/macro-ambiguity.md Illustrates FOLLOW set calculations for complex macro patterns, demonstrating intersections and token set determination. ```text FOLLOW(`$( $d:ident $e:expr )*`) = FOLLOW(`$e:expr`) ``` ```text FOLLOW(`$( $d:ident $e:expr )* $(;)*`) = FOLLOW(`$e:expr`) ∩ ANYTOKEN = FOLLOW(`$e:expr`) ``` ```text FOLLOW(`$( $d:ident $e:expr )* $(;)* $( f |)+`) = ANYTOKEN ``` -------------------------------- ### Serve Reference and Deny Warnings Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/tooling/building.md Serve the Reference documentation with mdbook, enabling SPEC_DENY_WARNINGS=1 to treat all mdbook-spec warnings as errors, useful for CI. ```sh SPEC_DENY_WARNINGS=1 mdbook serve --open ``` -------------------------------- ### Example: Using the C ABI Source: https://github.com/rust-lang/reference.git/blob/master/src/items/external-blocks.md Shows how to declare an external function using the standard "C" ABI, which typically matches the default ABI of the dominant C compiler for the target platform. ```rust unsafe extern "C" ``` -------------------------------- ### Outer Attributes Example Source: https://github.com/rust-lang/reference.git/blob/master/src/attributes.md Shows examples of outer attributes, which apply to the item immediately following them, such as tests, conditional compilation, and lint suppression. ```rust // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; ``` -------------------------------- ### Serve and Auto-Reload Reference with mdbook Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/tooling/building.md Launch a local web server for the Reference documentation. It rebuilds and reloads the browser on file changes. ```sh mdbook serve --open ``` -------------------------------- ### Importing Extern Prelude (Error Example) Source: https://github.com/rust-lang/reference.git/blob/master/src/items/use-declarations.md The `::` prefix, representing the extern prelude, cannot be directly imported. This example shows a compile-time error when attempting to import it. ```rust use ::{self as root}; //~ Error ``` -------------------------------- ### Example: Interface to Windows API with System ABI Source: https://github.com/rust-lang/reference.git/blob/master/src/items/external-blocks.md Demonstrates how to declare an external function block using the `extern` keyword with the "system" ABI, often used for interfacing with the Windows API. ```rust unsafe extern "system" { /* ... */ } ``` -------------------------------- ### Examples of Invalid Integer Literals Source: https://github.com/rust-lang/reference.git/blob/master/src/tokens.md Shows examples of integer literals that are not accepted by the Rust compiler, often due to invalid characters or incorrect formatting. ```rust # #[cfg(false)] { 0invalidSuffix; 123AFB43; 0b010a; 0xAB_CD_EF_GH; 0b1111_f32; # } ``` -------------------------------- ### Rust Canonical Path Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/paths.md Demonstrates the canonical paths for various items including modules, structs, traits, and implementations. Comments indicate the expected canonical path for each item. ```rust mod a { // crate::a pub struct Struct; // crate::a::Struct pub trait Trait { // crate::a::Trait fn f(&self); // crate::a::Trait::f } impl Trait for Struct { fn f(&self) {} // ::f } impl Struct { fn g(&self) {} // ::g } } mod without { // crate::without fn canonicals() { // crate::without::canonicals struct OtherStruct; // None trait OtherTrait { fn g(&self); } impl OtherTrait for OtherStruct { fn g(&self) {} } impl OtherTrait for crate::a::Struct { fn g(&self) {} } impl crate::a::Trait for OtherStruct { fn f(&self) {} } } } # fn main() {} ``` -------------------------------- ### Rust Macro Namespace Collision Example Source: https://github.com/rust-lang/reference.git/blob/master/src/names/namespaces.md Demonstrates how `use` imports prevent duplicate bindings, even for macros from different sub-namespaces. This example will result in an error. ```rust #[macro_export] macro_rules! mymac { () => {}; } use myattr::mymac; // error[E0252]: the name `mymac` is defined multiple times. ``` -------------------------------- ### Rust Trait Implementation Example Source: https://github.com/rust-lang/reference.git/blob/master/src/items/associated-items.md Provides an example of implementing the `Shape` trait for a `Circle` struct. This demonstrates how to fulfill the contract defined by the trait's methods. ```rust # type Surface = i32; # type BoundingBox = i32; # trait Shape { # fn draw(&self, surface: Surface); # fn bounding_box(&self) -> BoundingBox; # } # struct Circle { // ... } impl Shape for Circle { // ... # fn draw(&self, _: Surface) {} # fn bounding_box(&self) -> BoundingBox { 0i32 } } # impl Circle { # fn new() -> Circle { Circle{} } # } # let circle_shape = Circle::new(); let bounding_box = circle_shape.bounding_box(); ``` -------------------------------- ### Tool Attribute Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/attributes.md Shows how to use tool-specific attributes like `rustfmt::skip` to control external tools and `clippy::cyclomatic_complexity` to configure linter thresholds. ```rust // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} ``` -------------------------------- ### Example: Using System-unwind ABI Source: https://github.com/rust-lang/reference.git/blob/master/src/items/external-blocks.md Shows the declaration using the "system-unwind" ABI, similar to "system" but with distinct unwinding behavior. ```rust extern "system-unwind" ``` -------------------------------- ### Type Path Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/paths.md Illustrates the usage of type paths in various contexts, including trait implementations, generic type parameters, and type aliases. ```rust # mod ops { # pub struct Range {f1: T} # pub trait Index {} # pub struct Example<'a> {f1: &'a i32} # } # struct S; impl ops::Index> for S { /*...*/ } fn i<'a>() -> impl Iterator> { // ... # const EXAMPLE: Vec> = Vec::new(); # EXAMPLE.into_iter() } type G = std::boxed::Box isize>; ``` -------------------------------- ### Rust Trait Implementation Example Source: https://github.com/rust-lang/reference.git/blob/master/src/items/implementations.md Shows how to implement traits for a custom struct, including associated functions and methods. This example demonstrates implementing `Copy`, `Clone`, and a custom `Shape` trait for a `Circle` struct. ```rust # #[derive(Copy, Clone)] # struct Point {x: f64, y: f64}; # type Surface = i32; # struct BoundingBox {x: f64, y: f64, width: f64, height: f64}; # trait Shape { fn draw(&self, s: Surface); fn bounding_box(&self) -> BoundingBox; } # fn do_draw_circle(s: Surface, c: Circle) { } struct Circle { radius: f64, center: Point, } impl Copy for Circle {} impl Clone for Circle { fn clone(&self) -> Circle { *self } } impl Shape for Circle { fn draw(&self, s: Surface) { do_draw_circle(s, *self); } fn bounding_box(&self) -> BoundingBox { let r = self.radius; BoundingBox { x: self.center.x - r, y: self.center.y - r, width: 2.0 * r, height: 2.0 * r, } } } ``` -------------------------------- ### Example of a Naked Function in Rust Source: https://github.com/rust-lang/reference.git/blob/master/src/attributes/codegen.md This example demonstrates how to define a naked function using the `#[unsafe(naked)]` attribute. It requires the `naked_asm!` macro for the function body and must adhere to safety requirements, including respecting the calling convention and not falling through. ```rust # #[cfg(target_arch = "x86_64")] { /// Adds 3 to the given number. // SAFETY: The body respects the "sysv64" calling convention, // upholds the signature, and does not fall through. #[unsafe(naked)] pub extern "sysv64" fn add_n(number: u64) -> u64 { core::arch::naked_asm!( "add rdi, {}", "mov rax, rdi", "ret", const 3, ) } # } ``` -------------------------------- ### Markdown Link Examples Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/formatting/markdown.md Illustrates how to use shortcut and reference-style links in markdown. Ensure link references are sorted at the bottom of the file or section. ```markdown Example of shortcut link: [enumerations] Example of reference link with label: [block expression][block] [block]: expressions/block-expr.md [enumerations]: types/enum.md ``` -------------------------------- ### Implement Diverging Functions Source: https://github.com/rust-lang/reference.git/blob/master/src/types/never.md Examples of functions that never return using the '!' type. ```rust fn foo() -> ! { panic!("This call never returns."); } ``` ```rust unsafe extern "C" { pub safe fn no_return_extern_func() -> !; } ``` -------------------------------- ### Example: Using Cdecl ABI Source: https://github.com/rust-lang/reference.git/blob/master/src/items/external-blocks.md Demonstrates the "cdecl" ABI, suitable for x86_32 targets, which is a common calling convention for C code. ```rust unsafe extern "cdecl" ``` -------------------------------- ### Define Inline Module Source: https://github.com/rust-lang/reference.git/blob/master/src/items/modules.md Example of a module containing type aliases and functions. ```rust mod math { type Complex = (f64, f64); fn sin(f: f64) -> f64 { /* ... */ # unimplemented!(); } fn cos(f: f64) -> f64 { /* ... */ # unimplemented!(); } fn tan(f: f64) -> f64 { /* ... */ # unimplemented!(); } } ``` -------------------------------- ### Array and Slice Indexing Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/array-expr.md Demonstrates basic array indexing, multidimensional access, and out-of-bounds behavior including warnings and panics. ```rust // lint is deny by default. #![warn(unconditional_panic)] ([1, 2, 3, 4])[2]; // Evaluates to 3 let b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; b[1][2]; // multidimensional array indexing let x = (["a", "b"])[10]; // warning: index out of bounds let n = 10; let y = (["a", "b"])[n]; // panics let arr = ["a", "b"]; arr[10]; // warning: index out of bounds ``` -------------------------------- ### Byte literal expressions Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/literal-expr.md Examples of byte literals representing u8 values. ```rust b'R'; // 82 b'\''; // 39 b'\x52'; // 82 b'\xA0'; // 160 ``` -------------------------------- ### While Let Or-Pattern Example Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/loop-expr.md Demonstrates using `while let` with multiple `|` patterns to match different values. This allows for more flexible conditional looping based on destructured data. ```rust let mut vals = vec![2, 3, 1, 2, 2]; while let Some(v @ 1) | Some(v @ 2) = vals.pop() { // Prints 2, 2, then 1 println!("{}", v); } ``` -------------------------------- ### Rust Code Demonstrating Undefined Behavior Source: https://github.com/rust-lang/reference.git/blob/master/src/behavior-considered-undefined.md These examples illustrate undefined behavior in Rust. The first snippet shows reinterpreting a pointer with provenance as an integer, which is disallowed. The second snippet demonstrates rearranging the bytes of a pointer with provenance and reinterpreting them as a reference, also leading to undefined behavior. Both examples are marked with `compile_fail`. ```rust # use core::mem::MaybeUninit; # use core::ptr; // We cannot reinterpret a pointer with provenance as an integer, // as then the bytes of the integer will have provenance. const _: usize = { let ptr = &0; unsafe { (&raw const ptr as *const usize).read() } }; // We cannot rearrange the bytes of a pointer with provenance and // then interpret them as a reference, as then a value holding // pointer data will have pointer fragments in the wrong order. const _: &i32 = { let mut ptr = &0; let ptr_bytes = &raw mut ptr as *mut MaybeUninit::; unsafe { ptr::swap(ptr_bytes.add(1), ptr_bytes.add(2)) }; ptr }; ``` -------------------------------- ### Serve Reference with External Links Source: https://github.com/rust-lang/reference.git/blob/master/dev-guide/src/tooling/building.md Serve the Reference documentation using mdbook, setting SPEC_RELATIVE=0 to ensure links point to the external Rust documentation site instead of using relative paths. ```sh SPEC_RELATIVE=0 mdbook serve --open ``` -------------------------------- ### Declare Stack and Heap Arrays Source: https://github.com/rust-lang/reference.git/blob/master/src/types/array.md Examples of stack-allocated arrays and heap-allocated boxed arrays. ```rust // A stack-allocated array let array: [i32; 3] = [1, 2, 3]; // A heap-allocated array, coerced to a slice let boxed_array: Box<[i32]> = Box::new([1, 2, 3]); ``` -------------------------------- ### Static Item Execution Output Source: https://github.com/rust-lang/reference.git/blob/master/src/items/static-items.md The output produced by the generic static item example. ```text default_impl: counter was 0 default_impl: counter was 1 blanket_impl: counter was 0 blanket_impl: counter was 1 ``` -------------------------------- ### Diverging Loop Behavior Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/loop-expr.md Examples showing how loop divergence is determined by the break operands. ```rust fn diverging_loop_with_break(condition: bool) -> ! { // This loop is diverging because all `break` operands are diverging. loop { if condition { break loop {}; } else { break panic!(); } } } ``` ```rust fn loop_with_non_diverging_break(condition: bool) -> ! { // The type of this loop is i32 even though one of the breaks is // diverging. loop { if condition { break loop {}; } else { break 123i32; } } // ERROR: expected `!`, found `i32` } ``` -------------------------------- ### Item Declaration Scope Example Source: https://github.com/rust-lang/reference.git/blob/master/src/statements.md Demonstrates that inner functions cannot access variables from the outer scope. ```rust fn outer() { let outer_var = true; fn inner() { /* outer_var is not in scope here */ } inner(); } ``` -------------------------------- ### Basic Inline Assembly Example Source: https://github.com/rust-lang/reference.git/blob/master/src/inline-assembly.md Demonstrates multiplying a `u64` variable by 6 using inline assembly on x86-64. Ensure the target architecture supports inline assembly. ```rust # #[cfg(target_arch = "x86_64")] { use std::arch::asm; // Multiply x by 6 using shifts and adds let mut x: u64 = 4; unsafe { asm!( "mov {tmp}, {x}", "shl {tmp}, 1", "shl {x}, 2", "add {x}, {tmp}", x = inout(reg) x, tmp = out(reg) _, ); } assert_eq!(x, 4 * 6); # } ``` -------------------------------- ### Implement generic associated types Source: https://github.com/rust-lang/reference.git/blob/master/src/items/associated-items.md Example of using generic associated types (GATs) with where clauses. ```rust struct ArrayLender<'a, T>(&'a mut [T; 16]); trait Lend { // Generic associated type declaration type Lender<'a> where Self: 'a; fn lend<'a>(&'a mut self) -> Self::Lender<'a>; } impl Lend for [T; 16] { // Generic associated type definition type Lender<'a> = ArrayLender<'a, T> where Self: 'a; fn lend<'a>(&'a mut self) -> Self::Lender<'a> { ArrayLender(self) } } fn borrow<'a, T: Lend>(array: &'a mut T) -> ::Lender<'a> { array.lend() } fn main() { let mut array = [0usize; 16]; let lender = borrow(&mut array); } ``` -------------------------------- ### Example: Using C-unwind ABI Source: https://github.com/rust-lang/reference.git/blob/master/src/items/external-blocks.md Illustrates the use of the "C-unwind" ABI, which is identical to the "C" ABI but specifies different behavior when the callee unwinds. ```rust extern "C-unwind" ``` -------------------------------- ### Basic Dereferencing Examples Source: https://github.com/rust-lang/reference.git/blob/master/src/expressions/operator-expr.md Demonstrates the basic usage of the dereference operator (*) with immutable and mutable references, and with a Box. ```rust # struct NoCopy; let a = &7; assert_eq!(*a, 7); let b = &mut 9; *b = 11; assert_eq!(*b, 11); let c = Box::new(NoCopy); let d: NoCopy = *c; ```