The Rust Reference › The `unsafe` keyword › Unsafe blocks (`unsafe {}`)

A block of code can be prefixed with the `unsafe` keyword to permit using the unsafe actions as defined in the [Unsafety] chapter, such as calling other unsafe functions or dereferencing raw pointers.
By default, the body of an unsafe function is also considered to be an unsafe block; this can be changed by enabling the [`unsafe_op_in_unsafe_fn`] lint.
By putting operations into an unsafe block, the programmer states that they have taken care of satisfying the extra safety conditions of all operations inside that block.
Unsafe blocks are the logical dual to unsafe functions: where unsafe functions define a proof obligation that callers must uphold, unsafe blocks state that all relevant proof obligations of functions or operations called inside the block have been discharged. There are many ways to discharge proof obligations; for example, there could be run-time checks or data structure invariants that guarantee that certain properties are definitely true, or the unsafe block could be inside an `unsafe fn`, in which case the block can use the proof obligations of that function to discharge the proof obligations arising inside the block.
Unsafe blocks are used to wrap foreign libraries, make direct use of hardware or implement features not directly present in the language. For example, Rust provides the language features necessary to implement memory-safe concurrency in the language but the implementation of threads and message passing in the standard library uses unsafe blocks.
Rust's type system is a conservative approximation of the dynamic safety requirements, so in some cases there is a performance cost to using safe code. For example, a doubly-linked list is not a tree structure and can only be represented with reference-counted pointers in safe code. By using `unsafe` blocks to represent the reverse links as raw pointers, it can be implemented without reference counting. (See "Learn Rust With Entirely Too Many Linked Lists" for a more in-depth exploration of this particular example.)

The `unsafe` keyword
Unsafe blocks (`unsafe {}`)


The Rust Reference › The `unsafe` keyword › Unsafe traits (`unsafe trait`)

An unsafe trait is a trait that comes with extra safety conditions that must be upheld by *implementations* of the trait. The unsafe trait should come with documentation explaining what those extra safety conditions are.
Such a trait must be prefixed with the keyword `unsafe` and can only be implemented by `unsafe impl` blocks.

The `unsafe` keyword
Unsafe traits (`unsafe trait`)


The Rust Reference › The `unsafe` keyword › Unsafe trait implementations (`unsafe impl`)

When implementing an unsafe trait, the implementation needs to be prefixed with the `unsafe` keyword. By writing `unsafe impl`, the programmer states that they have taken care of satisfying the extra safety conditions required by the trait.
Unsafe trait implementations are the logical dual to unsafe traits: where unsafe traits define a proof obligation that implementations must uphold, unsafe implementations state that all relevant proof obligations have been discharged.


The Rust Reference › The `unsafe` keyword › Unsafe external blocks (`unsafe extern`)

The programmer who declares an [external block] must assure that the signatures of the items contained within are correct. Failing to do so may lead to undefined behavior.  That this obligation has been met is indicated by writing `unsafe extern`.
[!EDITION-2024]
Prior to edition 2024, `extern` blocks were allowed without being qualified as `unsafe`.


The Rust Reference › The `unsafe` keyword › Unsafe attributes (`#[unsafe(attr)]`)

An [unsafe attribute] is one that has extra safety conditions that must be upheld when using the attribute. The compiler cannot check whether these conditions have been upheld.  To assert that they have been, these attributes must be wrapped in `unsafe(..)`, e.g. `#[unsafe(no_mangle)]`.

The `unsafe` keyword
Unsafe attributes (`#[unsafe(attr)]`)


The Rust Reference › Behavior considered undefined

Rust code is incorrect if it exhibits any of the behaviors in the following list. This includes code within `unsafe` blocks and `unsafe` functions. `unsafe` only means that avoiding undefined behavior is on the programmer; it does not change anything about the fact that Rust programs must never cause undefined behavior.
It is the programmer's responsibility when writing `unsafe` code to ensure that any safe code interacting with the `unsafe` code cannot trigger these behaviors. `unsafe` code that satisfies this property for any safe client is called *sound*; if `unsafe` code can be misused by safe code to exhibit undefined behavior, it is *unsound*.
The following list is not exhaustive; it may grow or shrink. There is no formal model of Rust's semantics for what is and is not allowed in unsafe code, so there may be more behavior considered unsafe. We also reserve the right to make some of the behavior in that list defined in the future. In other words, this list does not say that anything will *definitely* always be undefined in all future Rust versions (but we might make such commitments for some list items in the future).
Please read the [Rustonomicon] before writing unsafe code.
* Data races.
* Accessing (loading from or storing to) a place that is [dangling] or [based on a misaligned pointer].
* Performing an offsetting place projection that violates the requirements of in-bounds pointer arithmetic. An offsetting place projection is a field expression, a tuple index expression, or an array/slice index expression.
* Breaking the pointer aliasing rules. The exact aliasing rules are not determined yet, but here is an outline of the general principles:


The Rust Reference › Behavior considered undefined

`&T` must point to memory that is not mutated while they are live (except for data inside an [`UnsafeCell<U>`]), and `&mut T` must point to memory that is not read or written by any pointer not derived from the reference and that no other reference points to while they are live. `Box<T>` is treated similar to `&'static mut T` for the purpose of these rules. The exact liveness duration is not specified, but some bounds exist:
  * For references, the liveness duration is upper-bounded by the syntactic lifetime assigned by the borrow checker; it cannot be live any *longer* than that lifetime.
  * Each time a reference or box is dereferenced or reborrowed, it is considered live.
  * Each time a reference or box is passed to or returned from a function, it is considered live.
  * When a reference (but not a `Box`!) is passed to a function, it is live at least as long as that function call, again except if the `&T` contains an [`UnsafeCell<U>`].
  All this also applies when values of these types are passed in a (nested) field of a compound type, but not behind pointer indirections.
* Mutating immutable bytes. All bytes reachable through a [const-promoted] expression are immutable, as well as bytes reachable through borrows in `static` and `const` initializers that have been [lifetime-extended] to `'static`. The bytes owned by an immutable binding or immutable `static` are immutable, unless those bytes are part of an [`UnsafeCell<U>`].
  Moreover, the bytes [pointed to] by a shared reference, including transitively through other references (both shared and mutable) and `Box`es, are immutable; transitivity includes those references stored in fields of compound types.


The Rust Reference › Behavior considered undefined

A mutation is any write of more than 0 bytes which overlaps with any of the relevant bytes (even if that write does not change the memory contents).
* Invoking undefined behavior via compiler intrinsics.
* Executing code compiled with platform features that the current platform does not support (see [`target_feature`]), *except* if the platform explicitly documents this to be safe.
* Calling a function with the wrong call ABI, or unwinding past a stack frame that does not allow unwinding (e.g. by calling a `"C-unwind"` function imported or transmuted as a `"C"` function or function pointer).
* Producing an invalid value. "Producing" a value happens any time a value is assigned to or read from a place, passed to a function/primitive operation or returned from a function/primitive operation.
* Incorrect use of inline assembly. For more details, refer to the [rules] to follow when writing code that uses inline assembly.
* Violating assumptions of the Rust runtime. Most assumptions of the Rust runtime are currently not explicitly documented.
  * For assumptions specifically related to unwinding, see the panic documentation.
  * The runtime assumes that a Rust stack frame is not deallocated without executing destructors for local variables owned by the stack frame. This assumption can be violated by C functions like `longjmp`.
Undefined behavior affects the entire program. For example, calling a function in C that exhibits undefined behavior of C means your entire program contains undefined behaviour that can also affect the Rust code. And vice versa, undefined behavior in Rust can cause adverse affects on code executed by any FFI calls to other languages.


The Rust Reference › Behavior considered undefined › Pointed-to bytes

The span of bytes a pointer or reference "points to" is determined by the pointer value and the size of the pointee type (using `size_of_val`).

Behavior considered undefined
Pointed-to bytes


The Rust Reference › Behavior considered undefined › Places based on misaligned pointers

A place is said to be "based on a misaligned pointer" if the last `*` projection during place computation was performed on a pointer that was not aligned for its type. (If there is no `*` projection in the place expression, then this is accessing the field of a local or `static` and rustc will guarantee proper alignment. If there are multiple `*` projections, then each of them incurs a load of the pointer-to-be-dereferenced itself from memory, and each of these loads is subject to the alignment constraint. Note that some `*` projections can be omitted in surface Rust syntax due to automatic dereferencing; we are considering the fully expanded place expression here.)
For instance, if `ptr` has type `*const S` where `S` has an alignment of 8, then `ptr` must be 8-aligned or else `(*ptr).f` is "based on an misaligned pointer". This is true even if the type of the field `f` is `u8` (i.e., a type with alignment 1). In other words, the alignment requirement derives from the type of the pointer that was dereferenced, *not* the type of the field that is being accessed.
Note that a place based on a misaligned pointer only leads to undefined behavior when it is loaded from or stored to.
`&raw const`/`&raw mut` on such a place is allowed.
`&`/`&mut` on a place requires the alignment of the field type (or else the program would be "producing an invalid value"), which generally is a less restrictive requirement than being based on an aligned pointer.

Behavior considered undefined
Places based on misaligned pointers


The Rust Reference › Behavior considered undefined › Places based on misaligned pointers

Taking a reference will lead to a compiler error in cases where the field type might be more aligned than the type that contains it, i.e., `repr(packed)`. This means that being based on an aligned pointer is always sufficient to ensure that the new reference is aligned, but it is not always necessary.


The Rust Reference › Behavior considered undefined › Dangling pointers

A reference/pointer is "dangling" if not all of the bytes it [points to] are part of the same live allocation (so in particular they all have to be part of *some* allocation).
If the size is 0, then the pointer is trivially never "dangling" (even if it is a null pointer).
Note that dynamically sized types (such as slices and strings) point to their entire range, so it is important that the length [metadata] is never too large.
In particular, the dynamic size of a Rust value (as determined by `size_of_val`) must never exceed `isize::MAX`, since it is impossible for a single allocation to be larger than `isize::MAX`.

Behavior considered undefined
Dangling pointers


The Rust Reference › Behavior considered undefined › Invalid values

The Rust compiler assumes that all values produced during program execution are "valid", and producing an invalid value is hence immediate UB.
Whether a value is valid depends on the type:
* A [`bool`] value must be `false` (`0`) or `true` (`1`).
* A `fn` pointer value must be non-null.
* A `char` value must not be a surrogate (i.e., must not be in the range `0xD800..=0xDFFF`) and must be equal to or less than `char::MAX`.
* A `!` value must never exist.
* An integer (`i*`/`u*`), floating point value (`f*`), or raw pointer must be initialized, i.e., must not be obtained from uninitialized memory.
* A `str` value is treated like `[u8]`, i.e. it must be initialized.
* An `enum` must have a valid discriminant, and all fields of the variant indicated by that discriminant must be valid at their respective type.
* A `struct`, tuple, and array requires all fields/elements to be valid at their respective type.
* For a `union`, the exact validity requirements are not decided yet. Obviously, all values that can be created entirely in safe code are valid. If the union has a [zero-sized] field, then every possible value is valid. Further details are still being debated.
* A reference or [`Box<T>`] must be aligned and non-null, it cannot be [dangling], and it must point to a valid value (in case of dynamically sized types, using the actual dynamic type of the pointee as determined by the [metadata]). Note that the last point (about pointing to a valid value) remains a subject of some debate.

Behavior considered undefined
Invalid values


The Rust Reference › Behavior considered undefined › Invalid values

* The [metadata] of a wide reference, [`Box<T>`], or raw pointer must match the type of the [unsized tail]:
  * `dyn Trait` metadata must be a pointer to a compiler-generated vtable for `Trait`. (For raw pointers, this requirement remains a subject of some debate.)
  * Slice (`[T]`) and `str` metadata must be a valid `usize`.
  In addition, for a wide reference or [`Box<T>`], the metadata is invalid if it makes the total size of the pointed-to value (as determined by `size_of_val`) bigger than `isize::MAX`.
This bound is on the size of the entire pointed-to value, not just its unsized tail, and it constrains `dyn Trait` metadata just as it does a slice or `str` length. A valid vtable describes an erased type no larger than `isize::MAX`, but a sized prefix can still carry the total past the limit.
* If a type has a custom range of valid values, then a valid value must be in that range. In the standard library, this affects [`NonNull<T>`] and [`NonZero<T>`].
`rustc` achieves this with the unstable `rustc_layout_scalar_valid_range_*` attributes.
* **In [const contexts]**: In addition to what is described above, further provenance-related requirements apply during const evaluation. Any value that holds pure integer data (the `i*`/`u*`/`f*` types as well as `bool` and `char`, enum discriminants, and slice [metadata]) must not carry any provenance. Any value that holds pointer data (references, raw pointers, function pointers, and `dyn Trait` metadata) must either carry no provenance, or all bytes must be fragments of the same original pointer value in the correct order.


The Rust Reference › Behavior considered undefined › Invalid values

This implies that transmuting or otherwise reinterpreting a pointer (reference, raw pointer, or function pointer) into a non-pointer type (such as integers) is undefined behavior if the pointer had provenance.
All of the following are UB:
```rust,compile_fail
// 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::<u8>;
    unsafe { ptr::swap(ptr_bytes.add(1), ptr_bytes.add(2)) };
    ptr
};
```
**Note:** Uninitialized memory is also implicitly invalid for any type that has a restricted set of valid values. In other words, the only cases in which reading uninitialized memory is permitted are inside `union`s and in "padding" (the gaps between the fields of a type).


The Rust Reference › Behavior not considered `unsafe`

The Rust compiler does not consider the following behaviors _unsafe_, though a programmer may (should) find them undesirable, unexpected, or erroneous.
- Deadlocks
- Leaks of memory and other resources
- Exiting without calling destructors
- Exposing randomized base addresses through pointer leaks


The Rust Reference › Behavior not considered `unsafe` › Integer overflow

If a program contains arithmetic overflow, the programmer has made an error. In the following discussion, we maintain a distinction between arithmetic overflow and wrapping arithmetic. The first is erroneous, while the second is intentional.
When the programmer has enabled `debug_assert!` assertions (for example, by enabling a non-optimized build), implementations must insert dynamic checks that `panic` on overflow. Other kinds of builds may result in `panics` or silently wrapped values on overflow, at the implementation's discretion.
In the case of implicitly-wrapped overflow, implementations must provide well-defined (even if still considered erroneous) results by using two's complement overflow conventions.
The integral types provide inherent methods to allow programmers explicitly to perform wrapping arithmetic. For example, `i32::wrapping_add` provides two's complement, wrapping addition.
The standard library also provides a `Wrapping<T>` newtype which ensures all standard arithmetic operations for `T` have wrapping semantics.
See [RFC 560] for error conditions, rationale, and more details about integer overflow.

Behavior not considered `unsafe`
Integer overflow


The Rust Reference › Behavior not considered `unsafe` › Logic errors

Safe code may impose extra logical constraints that can be checked at neither compile-time nor runtime. If a program breaks such a constraint, the behavior may be unspecified but will not result in undefined behavior. This could include panics, incorrect results, aborts, and non-termination. The behavior may also differ between runs, builds, or kinds of build.
For example, implementing both `Hash` and `Eq` requires that values considered equal have equal hashes. Another example are data structures like `BinaryHeap`, `BTreeMap`, `BTreeSet`, `HashMap` and `HashSet` which describe constraints on the modification of their keys while they are in the data structure. Violating such constraints is not considered unsafe, yet the program is considered erroneous and its behavior unpredictable.

Behavior not considered `unsafe`
Logic errors


The Rust Reference › Constant evaluation

Constant evaluation is the process of computing the result of [expressions] during compilation. Only a subset of all expressions can be evaluated at compile-time.


The Rust Reference › Constant evaluation › Constant expressions

Certain forms of expressions, called constant expressions, can be evaluated at compile time.
Expressions in a [const context] must be constant expressions.
Expressions in const contexts are always evaluated at compile time.
Outside of const contexts, constant expressions *may* be, but are not guaranteed to be, evaluated at compile time.
Behaviors such as out of bounds [array indexing] or [overflow] are compiler errors if the value must be evaluated at compile time (i.e. in const contexts). Otherwise, these behaviors are warnings, but will likely panic at run-time.
The following expressions are constant expressions, so long as any operands are also constant expressions and do not cause any `Drop::drop` calls to be run.
* [Literals].
* [Const parameters].
* [Paths] to [functions] and [constants]. Recursively defining constants is not allowed.
* Paths to [statics] with these restrictions:
  * Writes to `static` items are not allowed in any constant evaluation context.
  * Reads from `extern` statics are not allowed in any constant evaluation context.
  * If the evaluation is *not* carried out in an initializer of a `static` item, then reads from any mutable `static` are not allowed. A mutable `static` is a `static mut` item, or a `static` item with an interior-mutable type.
  These requirements are checked only when the constant is evaluated. In other words, having such accesses syntactically occur in const contexts is allowed as long as they never get executed.
* [Tuple expressions].
* [Array expressions].
* [Struct expressions].
* [Block expressions], including `unsafe` and `const` blocks.
    * [let statements] and thus irrefutable [patterns], including mutable bindings
    * [assignment expressions]
    * [compound assignment expressions]
    * [expression statements]
* [Field expressions].

Constant evaluation
Constant expressions


The Rust Reference › Constant evaluation › Constant expressions

* Array and slice indexing expressions, where the index is a `usize`.
* [Range expressions].
* [Closure expressions] which don't capture variables from the environment.
* Built-in [negation], [arithmetic], [logical], [comparison] or [lazy boolean] operators used on integer and floating point types, `bool`, and `char`.
* All forms of [borrow]s, including raw borrows, except borrows of expressions whose temporary scopes would be extended (see [temporary lifetime extension]) to the end of the program and which are either:
  * Mutable borrows.
  * Shared borrows of expressions that result in values with [interior mutability].
```rust,compile_fail,E0764
  // Due to being in tail position, this borrow extends the scope of the
  // temporary to the end of the program. Since the borrow is mutable,
  // this is not allowed in a const expression.
  const C: &u8 = &mut 0; // ERROR not allowed
```
```rust,compile_fail,E0764
  // Const blocks are similar to initializers of `const` items.
  let _: &u8 = const { &mut 0 }; // ERROR not allowed
```
```rust,compile_fail,E0492
  # use core::sync::atomic::AtomicU8;
  // This is not allowed as 1) the temporary scope is extended to the
  // end of the program and 2) the temporary has interior mutability.
  const C: &AtomicU8 = &AtomicU8::new(0); // ERROR not allowed
```
```rust,compile_fail,E0492
  # use core::sync::atomic::AtomicU8;
  // As above.
  let _: &_ = const { &AtomicU8::new(0) }; // ERROR not allowed
```


The Rust Reference › Constant evaluation › Constant expressions

```rust
  # #![allow(static_mut_refs)]
  // Even though this borrow is mutable, it's not of a temporary, so
  // this is allowed.
  const C: &u8 = unsafe { static mut S: u8 = 0; &mut S }; // OK
```
```rust
  # use core::sync::atomic::AtomicU8;
  // Even though this borrow is of a value with interior mutability,
  // it's not of a temporary, so this is allowed.
  const C: &AtomicU8 = {
      static S: AtomicU8 = AtomicU8::new(0); &S // OK
  };
```
```rust
  # use core::sync::atomic::AtomicU8;
  // This shared borrow of an interior mutable temporary is allowed
  // because its scope is not extended.
  const C: () = { _ = &AtomicU8::new(0); }; // OK
```
```rust
  // Even though the borrow is mutable and the temporary lives to the
  // end of the program due to promotion, this is allowed because the
  // borrow is not in tail position and so the scope of the temporary
  // is not extended via temporary lifetime extension.
  const C: () = { let _: &'static mut [u8] = &mut []; }; // OK
  //                                              ~~
  //                                     Promoted temporary.
```
In other words --- to focus on what's allowed rather than what's not allowed --- shared borrows of interior mutable data and mutable borrows are only allowed in a [const context] when the borrowed [place expression] is *transient*, *indirect*, or *static*.
A place expression is *transient* if it is a variable local to the current const context or an expression whose temporary scope is contained inside the current const context.


The Rust Reference › Constant evaluation › Constant expressions

```rust
// The borrow is of a variable local to the initializer, therefore
// this place expression is transient.
const C: () = { let mut x = 0; _ = &mut x; };
```
```rust
// The borrow is of a temporary whose scope has not been extended,
// therefore this place expression is transient.
const C: () = { _ = &mut 0u8; };
```
```rust
// When a temporary is promoted but not lifetime extended, its
// place expression is still treated as transient.
const C: () = { let _: &'static mut [u8] = &mut []; };
```
A place expression is *indirect* if it is a [dereference expression].
```rust
const C: () = { _ = &mut *(&mut 0); };
```
A place expression is *static* if it is a `static` item.
```rust
const C: &u8 = unsafe { static mut S: u8 = 0; &mut S };
```
One surprising consequence of these rules is that we allow this,
```rust
const C: &[u8] = { let x: &mut [u8] = &mut []; x }; // OK
//                                    ~~~~~~~
// Empty arrays are promoted even behind mutable borrows.
```
but we disallow this similar code:
```rust,compile_fail,E0764
const C: &[u8] = &mut []; // ERROR
//               ~~~~~~~
//           Tail expression.
```


The Rust Reference › Constant evaluation › Constant expressions

The difference between these is that, in the first, the empty array is [promoted] but its scope does not undergo [temporary lifetime extension], so we consider the [place expression] to be transient (even though after promotion the place indeed lives to the end of the program). In the second, the scope of the empty array temporary does undergo lifetime extension, and so it is rejected due to being a mutable borrow of a lifetime-extended temporary (and therefore borrowing a non-transient place expression).
The effect is surprising because temporary lifetime extension, in this case, causes less code to compile than would without it.
See issue #143129 for more details.
* [Dereference expressions].
```rust,no_run
  # use core::cell::UnsafeCell;
  const _: u8 = unsafe {
      let x: *mut u8 = &raw mut *&mut 0;
      //                        ^^^^^^^
      //             Dereference of mutable reference.
      *x = 1; // Dereference of mutable pointer.
      *(x as *const u8) // Dereference of constant pointer.
  };
  const _: u8 = unsafe {
      let x = &UnsafeCell::new(0);
      *x.get() = 1; // Mutation of interior mutable value.
      *x.get()
  };
```
* [Grouped] expressions.
* [Cast] expressions, except
  * pointer to address casts and
  * function pointer to address casts.
* Calls of [const functions] and const methods.
* [loop] and [while] expressions.
* [if] and [match] expressions.


The Rust Reference › Constant evaluation › Const context

A _const context_ is one of the following:
* [Array type length expressions]
* Array repeat length expressions
* The initializer of
  * [constants]
  * [statics]
  * [enum discriminants]
* A [const generic argument]
* A [const block]
Array type length expressions, array repeat length expressions, and const generic arguments are restricted in their use of outer generic parameters: such an expression must either be a single const generic parameter, or an expression that does not reference any generic parameters.


The Rust Reference › Constant evaluation › Const functions

A _const function_ is a function that can be called from a const context. It is defined with the `const` qualifier, and also includes [tuple struct] and [tuple enum variant] constructors.
```rust
const fn square(x: i32) -> i32 { x * x }

const VALUE: i32 = square(12);
```
When called from a const context, a const function is interpreted by the compiler at compile time. The interpretation happens in the environment of the compilation target and not the host. So `usize` is `32` bits if you are compiling against a `32` bit system, irrelevant of whether you are building on a `64` bit or a `32` bit system.
When a const function is called from outside a const context, it behaves the same as if it did not have the `const` qualifier.
The body of a const function may only use [constant expressions].
Const functions are not allowed to be [async].
The types of a const function's parameters and return type are restricted to those that are compatible with a const context.


The Rust Reference › Application binary interface (ABI)

This section documents features that affect the ABI of the compiled output of a crate.
See *[extern functions]* for information on specifying the ABI for exporting functions. See *[external blocks]* for information on specifying the ABI for linking external libraries.


The Rust Reference › Application binary interface (ABI) › The `used` attribute

The *`used` [attribute]* forces a [static] to be kept in the output object file (.o, .rlib, etc., excluding final binaries) even if it's never used or referenced by any other item in the crate. The linker, however, is still free to remove it.
```rust
// lib.rs

// This is kept because of `#[used]`.
#[used]
static S1: u8 = 0;

// This is removable because it's unused.
#[allow(dead_code)]
static S2: u8 = 0;

// This is kept because it's publicly reachable.
pub static S3: u8 = 0;

// This is kept because it's referenced by a publicly
// reachable function.
static S4: u8 = 0;
#[unsafe(no_mangle)] pub fn f4() -> &'static u8 { &S4 }

// This is removable because it's referenced only by a
// private, unused (dead) function.
static S5: u8 = 0;
#[allow(dead_code)]
fn f5() -> &'static u8 { &S5 }
```
```console
$ rustc -O --emit=obj --crate-type=rlib lib.rs
$ LC_ALL=C nm -C lib.o
0000000000000000 R lib::S1
0000000000000000 R lib::S3
0000000000000000 r lib::S4
0000000000000000 T f4
```
The `used` attribute uses the [MetaWord] syntax.
The `used` attribute may only be applied to [`static` items].
Only the first use of `used` on an item has effect.
`rustc` lints against any use following the first.

Application binary interface (ABI)
The `used` attribute


The Rust Reference › Application binary interface (ABI) › The `no_mangle` attribute

The *`no_mangle` attribute* may be used on any [item] to disable standard symbol name mangling. The symbol for the item will be the identifier of the item's name.
Additionally, the item will be publicly exported from the produced library or object file, similar to the `used` attribute.
This attribute is unsafe as an unmangled symbol may collide with another symbol with the same name (or with a well-known symbol), leading to undefined behavior.
```rust
#[unsafe(no_mangle)]
extern "C" fn foo() {}
```
[!EDITION-2024]
Before the 2024 edition it is allowed to use the `no_mangle` attribute without the `unsafe` qualification.

Application binary interface (ABI)
The `no_mangle` attribute


The Rust Reference › Application binary interface (ABI) › The `link_section` attribute

The *`link_section` attribute* specifies the section of the object file that a [function] or [static]'s content will be placed into.
The `link_section` attribute uses the [MetaNameValueStr] syntax to specify the section name.
```rust,no_run
#[unsafe(no_mangle)]
#[unsafe(link_section = ".example_section")]
pub static VAR1: u32 = 1;
```
This attribute is unsafe as it allows users to place data and code into sections of memory not expecting them, such as mutable data into read-only areas.
Only the first use of `link_section` on an item has effect.
`rustc` lints against any use following the first with a future-compatibility warning. This may become an error in the future.
[!EDITION-2024]
Before the 2024 edition it is allowed to use the `link_section` attribute without the `unsafe` qualification.

Application binary interface (ABI)
The `link_section` attribute


The Rust Reference › Application binary interface (ABI) › The `export_name` attribute

The *`export_name` attribute* specifies the name of the symbol that will be exported on a [function] or [static].
The `export_name `attribute uses the [MetaNameValueStr] syntax to specify the symbol name.
```rust
#[unsafe(export_name = "exported_symbol_name")]
pub fn name_in_rust() { }
```
This attribute is unsafe as a symbol with a custom name may collide with another symbol with the same name (or with a well-known symbol), leading to undefined behavior.
Only the first use of `export_name` on an item has effect.
`rustc` lints against any use following the first with a future-compatibility warning. This may become an error in the future.
[!EDITION-2024]
Before the 2024 edition it is allowed to use the `export_name` attribute without the `unsafe` qualification.

Application binary interface (ABI)
The `export_name` attribute


The Rust Reference › The Rust runtime

This section documents features that define some aspects of the Rust runtime.


The Rust Reference › The Rust runtime › The `global_allocator` attribute

The *`global_allocator` attribute* selects a memory allocator.
```rust
use core::alloc::{GlobalAlloc, Layout};
use std::alloc::System;

struct MyAllocator;

unsafe impl GlobalAlloc for MyAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        unsafe { System.alloc(layout) }
    }
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        unsafe { System.dealloc(ptr, layout) }
    }
}

#[global_allocator]
static GLOBAL: MyAllocator = MyAllocator;
```
The `global_allocator` attribute uses the [MetaWord] syntax.
The `global_allocator` attribute may only be applied to a [static item] whose type implements the [`GlobalAlloc`] trait.
The `global_allocator` attribute may only be used once on an item.
The `global_allocator` attribute may only be used once in the crate graph.
The `global_allocator` attribute is exported from the standard library prelude.

The Rust runtime
The `global_allocator` attribute


The Rust Reference › The Rust runtime › The `windows_subsystem` attribute

The *`windows_subsystem` attribute* sets the [subsystem] when linking on a Windows target.
```rust
#![windows_subsystem = "windows"]
```
The `windows_subsystem` attribute uses the [MetaNameValueStr] syntax. Accepted values are `"console"` and `"windows"`.
The `windows_subsystem` attribute may only be applied to the crate root.
Only the first use of `windows_subsystem` has effect.
`rustc` lints against any use following the first. This may become an error in the future.
The `windows_subsystem` attribute is ignored on non-Windows targets and non-`bin` [crate types].
The `"console"` subsystem is the default. If a console process is run from an existing console then it will be attached to that console; otherwise a new console window will be created.
The `"windows"` subsystem will run detached from any existing console.
The `"windows"` subsystem is commonly used by GUI applications that do not want to display a console window on startup.

The Rust runtime
The `windows_subsystem` attribute


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification

This page documents the formal specification of the follow rules for [Macros By Example]. They were originally specified in [RFC 550], from which the bulk of this text is copied, and expanded upon in subsequent RFCs.


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions

- `macro`: anything invocable as `foo!(...)` in source code.
  - `MBE`: macro-by-example, a macro defined by `macro_rules`.
  - `matcher`: the left-hand-side of a rule in a `macro_rules` invocation, or a subportion thereof.
  - `macro parser`: the bit of code in the Rust parser that will parse the input using a grammar derived from all of the matchers.
  - `fragment`: The class of Rust syntax that a given matcher will accept (or "match").
  - `repetition` : a fragment that follows a regular repeating pattern
  - `NT`: non-terminal, the various "meta-variables" or repetition matchers that can appear in a matcher, specified in MBE syntax with a leading `$` character.
  - `simple NT`: a "meta-variable" non-terminal (further discussion below).
  - `complex NT`: a repetition matching non-terminal, specified via repetition operators (`*`, `+`, `?`).
  - `token`: an atomic element of a matcher; i.e. identifiers, operators, open/close delimiters, *and* simple NT's.
  - `token tree`: a tree structure formed from tokens (the leaves), complex NT's, and finite sequences of token trees.
  - `delimiter token`: a token that is meant to divide the end of one fragment and the start of the next fragment.
  - `separator token`: an optional delimiter token in an complex NT that separates each pair of elements in the matched repetition.
  - `separated complex NT`: a complex NT that has its own separator token.
  - `delimited sequence`: a sequence of token trees with appropriate open- and close-delimiters at the start and end of the sequence.
  - `empty fragment`: The class of invisible Rust syntax that separates tokens, i.e. whitespace, or (in some lexical contexts), the empty token sequence.
  - `fragment specifier`: The identifier in a simple NT that specifies which fragment the NT accepts.
  - `language`: a context-free language.


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions

Example:
```rust,compile_fail
macro_rules! i_am_an_mbe {
    (start $foo:expr $($i:ident),* end) => ($foo)
}
```
`(start $foo:expr $($i:ident),* end)` is a matcher. The whole matcher is a delimited sequence (with open- and close-delimiters `(` and `)`), and `$foo` and `$i` are simple NT's with `expr` and `ident` as their respective fragment specifiers.
`$(i:ident),*` is *also* an NT; it is a complex NT that matches a comma-separated repetition of identifiers. The `,` is the separator token for the complex NT; it occurs in between each pair of elements (if any) of the matched fragment.
Another example of a complex NT is `$(hi $e:expr ;)+`, which matches any fragment of the form `hi <expr>; hi <expr>; ...` where `hi <expr>;` occurs at least once. Note that this complex NT does not have a dedicated separator token.
(Note that Rust's parser ensures that delimited sequences always occur with proper nesting of token tree structure and correct matching of open- and close-delimiters.)
We will tend to use the variable "M" to stand for a matcher, variables "t" and "u" for arbitrary individual tokens, and the variables "tt" and "uu" for arbitrary token trees. (The use of "tt" does present potential ambiguity with its additional role as a fragment specifier; but it will be clear from context which interpretation is meant.)
"SEP" will range over separator tokens, "OP" over the repetition operators `*`, `+`, and `?`, "OPEN"/"CLOSE" over matching token pairs surrounding a delimited sequence (e.g. `[` and `]`).


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions

Greek letters "α" "β" "γ" "δ"  stand for potentially empty token-tree sequences. (However, the Greek letter "ε" (epsilon) has a special role in the presentation and does not stand for a token-tree sequence.)
  * This Greek letter convention is usually just employed when the presence of a sequence is a technical detail; in particular, when we wish to *emphasize* that we are operating on a sequence of token-trees, we will use the notation "tt ..." for the sequence, not a Greek letter.
Note that a matcher is merely a token tree. A "simple NT", as mentioned above, is an meta-variable NT; thus it is a non-repetition. For example, `$foo:ty` is a simple NT but `$($foo:ty)+` is a complex NT.
Note also that in the context of this formalism, the term "token" generally *includes* simple NTs.
Finally, it is useful for the reader to keep in mind that according to the definitions of this formalism, no simple NT matches the empty fragment, and likewise no token matches the empty fragment of Rust syntax. (Thus, the *only* NT that can match the empty fragment is a complex NT.) This is not actually true, because the `vis` matcher can match an empty fragment. Thus, for the purposes of the formalism, we will treat `$v:vis` as actually being `$($v:vis)?`, with a requirement that the matcher match an empty fragment.


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › The matcher invariants

To be valid, a matcher must meet the following three invariants. The definitions of FIRST and FOLLOW are described later.
1.  For any two successive token tree sequences in a matcher `M` (i.e. `M = ... tt uu ...`) with `uu ...` nonempty, we must have FOLLOW(`... tt`) ∪ {ε} ⊇ FIRST(`uu ...`).
1.  For any separated complex NT in a matcher, `M = ... $(tt ...) SEP OP ...`, we must have `SEP` ∈ FOLLOW(`tt ...`).
1.  For an unseparated complex NT in a matcher, `M = ... $(tt ...) OP ...`, if OP = `*` or `+`, we must have FOLLOW(`tt ...`) ⊇ FIRST(`tt ...`).
The first invariant says that whatever actual token that comes after a matcher, if any, must be somewhere in the predetermined follow set.  This ensures that a legal macro definition will continue to assign the same determination as to where `... tt` ends and `uu ...` begins, even as new syntactic forms are added to the language.
The second invariant says that a separated complex NT must use a separator token that is part of the predetermined follow set for the internal contents of the NT. This ensures that a legal macro definition will continue to parse an input fragment into the same delimited sequence of `tt ...`'s, even as new syntactic forms are added to the language.
The third invariant says that when we have a complex NT that can match two or more copies of the same thing with no separation in between, it must be permissible for them to be placed next to each other as per the first invariant. This invariant also requires they be nonempty, which eliminates a possible ambiguity.


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › The matcher invariants

**NOTE: The third invariant is currently unenforced due to historical oversight and significant reliance on the behaviour. It is currently undecided what to do about this going forward. Macros that do not respect the behaviour may become invalid in a future edition of Rust. See the [tracking issue].**


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FIRST and FOLLOW, informally

A given matcher M maps to three sets: FIRST(M), LAST(M) and FOLLOW(M).
Each of the three sets is made up of tokens. FIRST(M) and LAST(M) may also contain a distinguished non-token element ε ("epsilon"), which indicates that M can match the empty fragment. (But FOLLOW(M) is always just a set of tokens.)
Informally:
  * FIRST(M): collects the tokens potentially used first when matching a fragment to M.
  * LAST(M): collects the tokens potentially used last when matching a fragment to M.
  * FOLLOW(M): the set of tokens allowed to follow immediately after some fragment matched by M.
    In other words: t ∈ FOLLOW(M) if and only if there exists (potentially empty) token sequences α, β, γ, δ where:
      * M matches β,
      * t matches γ, and
      * The concatenation α β γ δ is a parseable Rust program.
We use the shorthand ANYTOKEN to denote the set of all tokens (including simple NTs). For example, if any token is legal after a matcher M, then FOLLOW(M) = ANYTOKEN.
(To review one's understanding of the above informal descriptions, the reader at this point may want to jump ahead to the examples of FIRST/LAST before reading their formal definitions.)


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FIRST, LAST › FIRST

Below are formal inductive definitions for FIRST and LAST.
"A ∪ B" denotes set union, "A ∩ B" denotes set intersection, and "A \ B" denotes set difference (i.e. all elements of A that are not present in B).
FIRST(M) is defined by case analysis on the sequence M and the structure of its first token-tree (if any):
  * if M is the empty sequence, then FIRST(M) = { ε },
  * if M starts with a token t, then FIRST(M) = { t },
    (Note: this covers the case where M starts with a delimited token-tree sequence, `M = OPEN tt ... CLOSE ...`, in which case `t = OPEN` and thus FIRST(M) = { `OPEN` }.)
    (Note: this critically relies on the property that no simple NT matches the empty fragment.)
  * Otherwise, M is a token-tree sequence starting with a complex NT: `M = $( tt ... ) OP α`, or `M = $( tt ... ) SEP OP α`, (where `α` is the (potentially empty) sequence of token trees for the rest of the matcher).
      * Let SEP\_SET(M) = { SEP } if SEP is present and ε ∈ FIRST(`tt ...`); otherwise SEP\_SET(M) = {}.
  * Let ALPHA\_SET(M) = FIRST(`α`) if OP = `*` or `?` and ALPHA\_SET(M) = {} if OP = `+`.
  * FIRST(M) = (FIRST(`tt ...`) \\ {ε}) ∪ SEP\_SET(M) ∪ ALPHA\_SET(M).


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FIRST, LAST › LAST

The definition for complex NTs deserves some justification. SEP\_SET(M) defines the possibility that the separator could be a valid first token for M, which happens when there is a separator defined and the repeated fragment could be empty. ALPHA\_SET(M) defines the possibility that the complex NT could be empty, meaning that M's valid first tokens are those of the following token-tree sequences `α`. This occurs when either `*` or `?` is used, in which case there could be zero repetitions. In theory, this could also occur if `+` was used with a potentially-empty repeating fragment, but this is forbidden by the third invariant.
From there, clearly FIRST(M) can include any token from SEP\_SET(M) or ALPHA\_SET(M), and if the complex NT match is nonempty, then any token starting FIRST(`tt ...`) could work too. The last piece to consider is ε. SEP\_SET(M) and FIRST(`tt ...`) \ {ε} cannot contain ε, but ALPHA\_SET(M) could. Hence, this definition allows M to accept ε if and only if ε ∈ ALPHA\_SET(M) does. This is correct because for M to accept ε in the complex NT case, both the complex NT and α must accept it. If OP = `+`, meaning that the complex NT cannot be empty, then by definition ε ∉ ALPHA\_SET(M). Otherwise, the complex NT can accept zero repetitions, and then ALPHA\_SET(M) = FOLLOW(`α`). So this definition is correct with respect to \varepsilon as well.
LAST(M), defined by case analysis on M itself (a sequence of token-trees):
  * if M is the empty sequence, then LAST(M) = { ε }
  * if M is a singleton token t, then LAST(M) = { t }


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FIRST, LAST › LAST

* if M is the singleton complex NT repeating zero or more times, `M = $( tt ... ) *`, or `M = $( tt ... ) SEP *`
      * Let sep_set = { SEP } if SEP present; otherwise sep_set = {}.
      * if ε ∈ LAST(`tt ...`) then LAST(M) = LAST(`tt ...`) ∪ sep_set
      * otherwise, the sequence `tt ...` must be non-empty; LAST(M) = LAST(`tt ...`) ∪ {ε}.
  * if M is the singleton complex NT repeating one or more times, `M = $( tt ... ) +`, or `M = $( tt ... ) SEP +`
      * Let sep_set = { SEP } if SEP present; otherwise sep_set = {}.
      * if ε ∈ LAST(`tt ...`) then LAST(M) = LAST(`tt ...`) ∪ sep_set
      * otherwise, the sequence `tt ...` must be non-empty; LAST(M) = LAST(`tt ...`)
  * if M is the singleton complex NT repeating zero or one time, `M = $( tt ...) ?`, then LAST(M) = LAST(`tt ...`) ∪ {ε}.
  * if M is a delimited token-tree sequence `OPEN tt ... CLOSE`, then LAST(M) = { `CLOSE` }.
  * if M is a non-empty sequence of token-trees `tt uu ...`,
      * If ε ∈ LAST(`uu ...`), then LAST(M) = LAST(`tt`) ∪ (LAST(`uu ...`) \ { ε }).
      * Otherwise, the sequence `uu ...` must be non-empty; then LAST(M) = LAST(`uu ...`).


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › Examples of FIRST and LAST

Below are some examples of FIRST and LAST. (Note in particular how the special ε element is introduced and eliminated based on the interaction between the pieces of the input.)
Our first example is presented in a tree structure to elaborate on how the analysis of the matcher composes. (Some of the simpler subtrees have been elided.)
```text
INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+   g
            ~~~~~~~~   ~~~~~~~                ~
                |         |                   |
FIRST:   { $d:ident }  { $e:expr }          { h }

INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+
            ~~~~~~~~~~~~~~~~~~             ~~~~~~~           ~~~
                        |                      |               |
FIRST:          { $d:ident }               { h, ε }         { f }

INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+   g
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~    ~~~~~~~~~   ~
                        |                       |              |       |
FIRST:        { $d:ident, ε }            {  h, ε, ;  }      { f }   { g }

INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+   g
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                                        |
FIRST:                       { $d:ident, h, ;,  f }
```
Thus:
 * FIRST(`$($d:ident $e:expr );* $( $(h)* );* $( f ;)+ g`) = { `$d:ident`, `h`, `;`, `f` }
Note however that:


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › Examples of FIRST and LAST

* FIRST(`$($d:ident $e:expr );* $( $(h)* );* $($( f ;)+ g)*`) = { `$d:ident`, `h`, `;`, `f`, ε }
Here are similar examples but now for LAST.
 * LAST(`$d:ident $e:expr`) = { `$e:expr` }
 * LAST(`$( $d:ident $e:expr );*`) = { `$e:expr`, ε }
 * LAST(`$( $d:ident $e:expr );* $(h)*`) = { `$e:expr`, ε, `h` }
 * LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+`) = { `;` }
 * LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+ g`) = { `g` }


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FOLLOW(M)

Finally, the definition for FOLLOW(M) is built up as follows. pat, expr, etc. represent simple nonterminals with the given fragment specifier.
  * FOLLOW(pat) = {`=>`, `,`, `=`, `|`, `if`, `in`}`.
  * FOLLOW(expr) = FOLLOW(expr_2021) = FOLLOW(stmt) =  {`=>`, `,`, `;`}`.
  * FOLLOW(ty) = FOLLOW(path) = {`{`, `[`, `,`, `=>`, `:`, `=`, `>`, `>>`, `;`, `|`, `as`, `where`, block nonterminals}.
  * FOLLOW(vis) = {`,`l any keyword or identifier except a non-raw `priv`; any token that can begin a type; ident, ty, and path nonterminals}.
  * FOLLOW(t) = ANYTOKEN for any other simple token, including block, ident, tt, item, lifetime, literal and meta simple nonterminals, and all terminals.
  * FOLLOW(M), for any other M, is defined as the intersection, as t ranges over (LAST(M) \ {ε}), of FOLLOW(t).
The tokens that can begin a type are, as of this writing, {`(`, `[`, `!`, `*`, `&`, `&&`, `?`, lifetimes, `>`, `>>`, `::`, any non-keyword identifier, `super`, `self`, `Self`, `extern`, `crate`, `$crate`, `_`, `for`, `impl`, `fn`, `unsafe`, `typeof`, `dyn`}, although this list may not be complete because people won't always remember to update the appendix when new ones are added.
Examples of FOLLOW for complex M:


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FOLLOW(M)

* FOLLOW(`$( $d:ident $e:expr )*`) = FOLLOW(`$e:expr`)
 * FOLLOW(`$( $d:ident $e:expr )* $(;)*`) = FOLLOW(`$e:expr`) ∩ ANYTOKEN = FOLLOW(`$e:expr`)
 * FOLLOW(`$( $d:ident $e:expr )* $(;)* $( f |)+`) = ANYTOKEN


The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › Examples of valid and invalid matchers

With the above specification in hand, we can present arguments for why particular matchers are legal and others are not.
 * `($ty:ty < foo ,)` : illegal, because FIRST(`< foo ,`) = { `<` } ⊈ FOLLOW(`ty`)
 * `($ty:ty , foo <)` : legal, because FIRST(`, foo <`) = { `,` }  is ⊆ FOLLOW(`ty`).
 * `($pa:pat $pb:pat $ty:ty ,)` : illegal, because FIRST(`$pb:pat $ty:ty ,`) = { `$pb:pat` } ⊈ FOLLOW(`pat`), and also FIRST(`$ty:ty ,`) = { `$ty:ty` } ⊈ FOLLOW(`pat`).
 * `( $($a:tt $b:tt)* ; )` : legal, because FIRST(`$b:tt`) = { `$b:tt` } is ⊆ FOLLOW(`tt`) = ANYTOKEN, as is FIRST(`;`) = { `;` }.
 * `( $($t:tt),* , $(t:tt),* )` : legal,  (though any attempt to actually use this macro will signal a local ambiguity error during expansion).
 * `($ty:ty $(; not sep)* -)` : illegal, because FIRST(`$(; not sep)* -`) = { `;`, `-` } is not in FOLLOW(`ty`).
 * `($($ty:ty)-+)` : illegal, because separator `-` is not in FOLLOW(`ty`).
 * `($($e:expr)*)` : illegal, because expr NTs are not in FOLLOW(expr NT).


The Rust Reference › Influences

Rust is not a particularly original language, with design elements coming from a wide range of sources. Some of these are listed below (including elements that have since been removed):
* SML, OCaml: algebraic data types, pattern matching, type inference, semicolon statement separation
* C++: references, RAII, smart pointers, move semantics, monomorphization, memory model
* ML Kit, Cyclone: region based memory management
* Haskell (GHC): typeclasses, type families
* Newsqueak, Alef, Limbo: channels, concurrency
* Erlang: message passing, thread failure, ~~linked thread failure~~, ~~lightweight concurrency~~
* Swift: optional bindings
* Scheme: hygienic macros
* C#: attributes
* Ruby: closure syntax, ~~block syntax~~
* NIL, Hermes: ~~typestate~~
* Unicode Annex #31: identifier and pattern syntax


The Rust Reference › Glossary › Abstract syntax tree

An ‘abstract syntax tree’, or ‘AST’, is an intermediate representation of the structure of the program when the compiler is compiling it.


The Rust Reference › Glossary › Alignment

The alignment of a value specifies what addresses values are preferred to start at. Always a power of two. References to a value must be aligned. More.


The Rust Reference › Glossary › Application binary interface (ABI)

An *application binary interface* (ABI) defines how compiled code interacts with other compiled code. With [`extern` blocks] and [`extern fn`], *ABI strings* affect:
- **Calling convention**: How function arguments are passed, values are returned (e.g., in registers or on the stack), and who is responsible for cleaning up the stack.
- **Unwinding**: Whether stack unwinding is allowed. For example, the `"C-unwind"` ABI allows unwinding across the FFI boundary, while the `"C"` ABI does not.

Glossary
Application binary interface (ABI)


The Rust Reference › Glossary › Arity

Arity refers to the number of arguments a function or operator takes. For some examples, `f(2, 3)` and `g(4, 6)` have arity 2, while `h(8, 2, 6)` has arity 3. The `!` operator has arity 1.


The Rust Reference › Glossary › Array

An array, sometimes also called a fixed-size array or an inline array, is a value describing a collection of elements, each selected by an index that can be computed at run time by the program. It occupies a contiguous region of memory.


The Rust Reference › Glossary › Associated item

An associated item is an item that is associated with another item. Associated items are defined in [implementations] and declared in [traits]. Only functions, constants, and type aliases can be associated. Contrast to a [free item].


The Rust Reference › Glossary › Blanket implementation

Any implementation where a type appears uncovered. `impl<T> Foo for T`, `impl<T> Bar<T> for T`, `impl<T> Bar<Vec<T>> for T`, and `impl<T> Bar<T> for Vec<T>` are considered blanket impls. However, `impl<T> Bar<Vec<T>> for Vec<T>` is not a blanket impl, as all instances of `T` which appear in this `impl` are covered by `Vec`.


The Rust Reference › Glossary › Bound

Bounds are constraints on a type or trait. For example, if a bound is placed on the argument a function takes, types passed to that function must abide by that constraint.


The Rust Reference › Glossary › Combinator

Combinators are higher-order functions that apply only functions and earlier defined combinators to provide a result from its arguments. They can be used to manage control flow in a modular fashion.


The Rust Reference › Glossary › Crate

A crate is the unit of compilation and linking. There are different [types of crates], such as libraries or executables. Crates may link and refer to other library crates, called external crates. A crate has a self-contained tree of [modules], starting from an unnamed root module called the crate root. [Items] may be made visible to other crates by marking them as public in the crate root, including through [paths] of public modules. More.


The Rust Reference › Glossary › Dispatch

Dispatch is the mechanism to determine which specific version of code is actually run when it involves polymorphism. Two major forms of dispatch are static dispatch and dynamic dispatch. Rust supports dynamic dispatch through the use of trait objects.


The Rust Reference › Glossary › Dynamically sized type

A dynamically sized type (DST) is a type without a statically known size or alignment.


The Rust Reference › Glossary › Entity

An [*entity*] is a language construct that can be referred to in some way within the source program, usually via a path. Entities include [types], [items], [generic parameters], [variable bindings], [loop labels], [lifetimes], [fields], [attributes], and [lints].


The Rust Reference › Glossary › Expression

An expression is a combination of values, constants, variables, operators and functions that evaluate to a single value, with or without side-effects.
For example, `2 + (3 * 4)` is an expression that returns the value 14.


The Rust Reference › Glossary › Free item

An [item] that is not a member of an [implementation], such as a *free function* or a *free const*. Contrast to an [associated item].


The Rust Reference › Glossary › Fundamental traits

A fundamental trait is one where adding an impl of it for an existing type is a breaking change. The `Fn` traits and `Sized` are fundamental.


The Rust Reference › Glossary › Fundamental type constructors

A fundamental type constructor is a type where implementing a blanket implementation over it is a breaking change. `&`, `&mut`, `Box`, and `Pin`  are fundamental.
Any time a type `T` is considered local, `&T`, `&mut T`, `Box<T>`, and `Pin<T>` are also considered local. Fundamental type constructors cannot cover other types. Any time the term "covered type" is used, the `T` in `&T`, `&mut T`, `Box<T>`, and `Pin<T>` is not considered covered.


The Rust Reference › Glossary › Inhabited

A type is inhabited if it has constructors and therefore can be instantiated. An inhabited type is not "empty" in the sense that there can be values of the type. Opposite of Uninhabited.


The Rust Reference › Glossary › Inherent implementation

An [implementation] that applies to a nominal type, not to a trait-type pair. More.


The Rust Reference › Glossary › Inherent method

A [method] defined in an [inherent implementation], not in a trait implementation.


The Rust Reference › Glossary › Initialized

A variable is initialized if it has been assigned a value and hasn't since been moved from. All other memory locations are assumed to be uninitialized. Only unsafe Rust can create a memory location without initializing it.


The Rust Reference › Glossary › Local trait

A `trait` which was defined in the current crate. A trait definition is local or not independent of applied type arguments. Given `trait Foo<T, U>`, `Foo` is always local, regardless of the types substituted for `T` and `U`.


The Rust Reference › Glossary › Local type

A `struct`, `enum`, or `union` which was defined in the current crate. This is not affected by applied type arguments. `struct Foo` is considered local, but `Vec<Foo>` is not. `LocalType<ForeignType>` is local. Type aliases do not affect locality.


The Rust Reference › Glossary › Module

A module is a container for zero or more [items]. Modules are organized in a tree, starting from an unnamed module at the root called the crate root or the root module. [Paths] may be used to refer to items from other modules, which may be restricted by [visibility rules]. More


The Rust Reference › Glossary › Name

A [*name*] is an [identifier] or [lifetime or loop label] that refers to an entity. A *name binding* is when an entity declaration introduces an identifier or label associated with that entity. [Paths], identifiers, and labels are used to refer to an entity.


The Rust Reference › Glossary › Name resolution

[*Name resolution*] is the compile-time process of tying [paths], [identifiers], and [labels] to entity declarations.


The Rust Reference › Glossary › Namespace

A *namespace* is a logical grouping of declared names based on the kind of entity the name refers to. Namespaces allow the occurrence of a name in one namespace to not conflict with the same name in another namespace.
Within a namespace, names are organized in a hierarchy, where each level of the hierarchy has its own collection of named entities.


The Rust Reference › Glossary › Nominal types

Types that can be referred to by a path directly. Specifically [enums], [structs], [unions], and [trait object types].


The Rust Reference › Glossary › Dyn-compatible traits

[Traits] that can be used in [trait object types] (`dyn Trait`). Only traits that follow specific rules are *dyn compatible*.
These were formerly known as *object safe* traits.


The Rust Reference › Glossary › Path

A [*path*] is a sequence of one or more path segments used to refer to an entity in the current scope or other levels of a namespace hierarchy.


The Rust Reference › Glossary › Prelude

Prelude, or The Rust Prelude, is a small collection of items - mostly traits - that are imported into every module of every crate. The traits in the prelude are pervasive.


The Rust Reference › Glossary › Scope

A [*scope*] is the region of source text where a named entity may be referenced with that name.


The Rust Reference › Glossary › Scrutinee

A scrutinee is the expression that is matched on in `match` expressions and similar pattern matching constructs. For example, in `match x { A => 1, B => 2 }`, the expression `x` is the scrutinee.


The Rust Reference › Glossary › Size

The size of a value has two definitions.
The first is that it is how much memory must be allocated to store that value.
The second is that it is the offset in bytes between successive elements in an array with that item type.
It is a multiple of the alignment, including zero. The size can change depending on compiler version (as new optimizations are made) and target platform (similar to how `usize` varies per-platform).
More.


The Rust Reference › Glossary › Slice

A slice is dynamically-sized view into a contiguous sequence, written as `[T]`.
It is often seen in its borrowed forms, either mutable or shared. The shared slice type is `&[T]`, while the mutable slice type is `&mut [T]`, where `T` represents the element type.


The Rust Reference › Glossary › Statement

A statement is the smallest standalone element of a programming language that commands a computer to perform an action.


The Rust Reference › Glossary › String literal

A string literal is a string stored directly in the final binary, and so will be valid for the `'static` duration.
Its type is `'static` duration borrowed string slice, `&'static str`.


The Rust Reference › Glossary › String slice

A string slice is the most primitive string type in Rust, written as `str`. It is often seen in its borrowed forms, either mutable or shared. The shared string slice type is `&str`, while the mutable string slice type is `&mut str`.
Strings slices are always valid UTF-8.


The Rust Reference › Glossary › Trait

A trait is a language item that is used for describing the functionalities a type must provide. It allows a type to make certain promises about its behavior.
Generic functions and generic structs can use traits to constrain, or bound, the types they accept.


The Rust Reference › Glossary › Turbofish

Paths with generic parameters in expressions must prefix the opening brackets with a `::`. Combined with the angular brackets for generics, this looks like a fish `::<>`. As such, this syntax is colloquially referred to as turbofish syntax.
Examples:
```rust
let ok_num = Ok::<_, ()>(5);
let vec = [1, 2, 3].iter().map(|n| n * 2).collect::<Vec<_>>();
```
This `::` prefix is required to disambiguate generic paths with multiple comparisons in a comma-separate list. See the bastion of the turbofish for an example where not having the prefix would be ambiguous.


The Rust Reference › Glossary › Uncovered type

A type which does not appear as an argument to another type. For example, `T` is uncovered, but the `T` in `Vec<T>` is covered. This is only relevant for type arguments.


The Rust Reference › Glossary › Undefined behavior

Compile-time or run-time behavior that is not specified. This may result in, but is not limited to: process termination or corruption; improper, incorrect, or unintended computation; or platform-specific results. More.


The Rust Reference › Glossary › Uninhabited

A type is uninhabited if it has no constructors and therefore can never be instantiated. An uninhabited type is "empty" in the sense that there are no values of the type. The canonical example of an uninhabited type is the [never type] `!`, or an enum with no variants `enum Never { }`. Opposite of Inhabited.


The Rust Reference › Glossary › Zero-sized type (ZST)

A type is zero sized (a ZST) if its size is 0. Such types have at most one possible value. Examples include:
- The [unit type] (see [layout.tuple.unit]).
- [Function items] (see [type.fn-item.intro]).
- The constructors of [tuple-like structs] (see [type.fn-item.intro]).
- The constructors of [tuple-like enum variants] (see [type.fn-item.intro]).
- `repr(Rust)` [structs] with no fields or where all fields are zero sized (see [layout.repr.rust.struct-zst]).
- `repr(C)` [structs] with no fields or where all fields are zero-sized (see [layout.repr.c.struct.size-field-offset]).
- `repr(transparent)` [structs] with no fields or where all fields are zero-sized (see [layout.repr.transparent.layout-abi]).
- `repr(Rust)` [enums] (without a [primitive representation] specified) with a single [field-struct-like variant], a single [unit-struct-like variant], or a single [tuple-struct-like variant] and where the struct-like thing has no fields or where all of the fields are zero sized (see [layout.repr.rust.enum-struct-like-zst]).
- [Arrays] of zero-sized types (see [layout.array]).
- [Arrays] of length zero (see [layout.array]).
- [Unions] of zero-sized types (see [items.union.common-storage]).


The Rust Reference › Glossary › Zero-sized type (ZST)

```rust
fn f() {}
struct S(u8);
enum E { V(u8) }
struct UnitLike;
struct NoFields {}
struct OnlyZST {
    f1: (),
    f2: [(); 10],
    f3: [u8; 0],
}
#[repr(C)]
struct C1 {}
#[repr(C)]
struct C2 {
    f1: (),
    f2: [(); 10],
    f3: [u8; 0],
    f4: C1,
}
#[repr(transparent)]
struct T1 {}
#[repr(transparent)]
struct T2 {
    f1: (),
    f2: [(); 10],
    f3: [u8; 0],
}
union U {
    f1: (),
    f2: [(); 10],
    f3: [u8; 0],
}
enum E2 {
    V1 { f1: (), f2: [(); 10] },
}
enum E3 {
    V1 {},
}
enum E4 {
    V1,
}
enum E5 {
    V1 ((), [(); 10]),
}
enum E6 {
    V1 (),
}

assert_eq!(0, size_of::<()>());
assert_eq!(0, size_of_val(&f));
assert_eq!(0, size_of_val(&S));
assert_eq!(0, size_of_val(&E::V));
assert_eq!(0, size_of::<UnitLike>());
assert_eq!(0, size_of::<NoFields>());
assert_eq!(0, size_of::<OnlyZST>());
assert_eq!(0, size_of::<C1>());
assert_eq!(0, size_of::<C2>());
assert_eq!(0, size_of::<T1>());
assert_eq!(0, size_of::<T2>());
assert_eq!(0, size_of::<[(); 10]>());
assert_eq!(0, size_of::<[u8; 0]>());
assert_eq!(0, size_of::<U>());
assert_eq!(0, size_of::<E2>());
assert_eq!(0, size_of::<E3>());
assert_eq!(0, size_of::<E4>());
assert_eq!(0, size_of::<E5>());
assert_eq!(0, size_of::<E6>());
```


Rust by Example › Rust by Example

Rust is a modern systems programming language focusing on safety, speed,
and concurrency. It accomplishes these goals by being memory safe without using
garbage collection.
Rust by Example (RBE) is a collection of runnable examples that illustrate various Rust
concepts and standard libraries. To get even more out of these examples, don't forget
to install Rust locally and check out the official docs.
Additionally for the curious, you can also check out the source code for this site.
Now let's begin!
- Hello World - Start with a traditional Hello World program.
- Primitives - Learn about signed integers, unsigned integers and other primitives.
- Custom Types - `struct` and `enum`.
- Variable Bindings - mutable bindings, scope, shadowing.
- Types - Learn about changing and defining types.
- Conversion - Convert between different types, such as strings, integers, and floats.
- Expressions - Learn about Expressions & how to use them.
- Flow of Control - `if`/`else`, `for`, and others.
- Functions - Learn about Methods, Closures and Higher Order Functions.
- Modules - Organize code using modules
- Crates - A crate is a compilation unit in Rust. Learn to create a library.
- Cargo - Go through some basic features of the official Rust package management tool.
- Attributes - An attribute is metadata applied to some module, crate or item.
- Generics - Learn about writing a function or data type which can work for multiple types of arguments.


Rust by Example › Rust by Example

- Scoping rules - Scopes play an important part in ownership, borrowing, and lifetimes.
- Traits - A trait is a collection of methods defined for an unknown type: `Self`
- Macros - Macros are a way of writing code that writes other code, which is known as metaprogramming.
- Error handling - Learn Rust way of handling failures.
- Std library types - Learn about some custom types provided by `std` library.
- Std misc - More custom types for file handling, threads.
- Testing - All sorts of testing in Rust.
- Unsafe Operations - Learn about entering a block of unsafe operations.
- Compatibility - Handling Rust's evolution and potential compatibility issues.
- Meta - Documentation, Benchmarking.


Rust by Example › Hello World

This is the source code of the traditional Hello World program.
```rust,editable
// This is a comment, and is ignored by the compiler.
// You can test this code by clicking the "Run" button over there ->
// or if you prefer to use your keyboard, you can use the "Ctrl + Enter"
// shortcut.

// This code is editable, feel free to hack it!
// You can always return to the original code by clicking the "Reset" button ->

// This is the main function.
fn main() {
    // Statements here are executed when the compiled binary is called.

    // Print text to the console.
    println!("Hello World!");
}
```
`println!` is a *macro* that prints text to the
console.
A binary can be generated using the Rust compiler: `rustc`.
```bash
$ rustc hello.rs
```
`rustc` will produce a `hello` binary that can be executed.
```bash
$ ./hello
Hello World!
```


Rust by Example › Hello World › Activity

Click 'Run' above to see the expected output. Next, add a new
line with a second `println!` macro so that the output shows:
```text
Hello World!
I'm a Rustacean!
```


Rust by Example › Comments

Any program requires comments, and Rust supports
a few different varieties:


Rust by Example › Comments › Regular Comments

These are ignored by the compiler:
* **Line comments**: Start with `//` and continue to the end of the line
* **Block comments**: Enclosed in `/* ... */` and can span multiple lines


Rust by Example › Comments › Documentation Comments (Doc Comments) which are parsed into HTML library documentation:

- `///` - Generates docs for the item that follows it
- `//!` - Generates docs for the enclosing item (typically used at the top of a file or module)
```rust,editable

fn main() {
    // Line comments start with two slashes.
    // Everything after the slashes is ignored by the compiler.

    // Example: This line won't execute
    // println!("Hello, world!");

    // Try removing the slashes above and running the code again.

    /*
      Block comments are useful for temporarily disabling code.
      They can also be nested: /* like this */ which makes it easy
      to comment out large sections quickly.
     */

    /*
     * Note: The asterisk column on the left is just for style -
     * it's not required by the language.
     */

    // Block comments make it easy to toggle code on/off by adding
    // or removing just one slash:

    /* <- Add a '/' here to uncomment the entire block below

    println!("Now");
    println!("everything");
    println!("executes!");
    // Line comments inside remain unaffected

    // */

    // Block comments can also be used within expressions:
    let x = 5 + /* 90 + */ 5;
    println!("Is `x` 10 or 100? x = {}", x);
}
```


Rust by Example › Comments › Documentation Comments (Doc Comments) which are parsed into HTML library documentation: › See also:

Library documentation


Rust by Example › Formatted print

Printing is handled by a series of `macros` defined in
`std::fmt` some of which are:
* `format!`: write formatted text to `String`
* `print!`: same as `format!` but the text is printed to the console
  (io::stdout).
* `println!`: same as `print!` but a newline is appended.
* `eprint!`: same as `print!` but the text is printed to the standard error
  (io::stderr).
* `eprintln!`: same as `eprint!` but a newline is appended.
All parse text in the same fashion. As a plus, Rust checks formatting
correctness at compile time.


Rust by Example › Formatted print

```rust,editable,ignore,mdbook-runnable
fn main() {
    // In general, the `{}` will be automatically replaced with any
    // arguments. These will be stringified.
    println!("{} days", 31);

    // Positional arguments can be used. Specifying an integer inside `{}`
    // determines which additional argument will be replaced. Arguments start
    // at 0 immediately after the format string.
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

    // As can named arguments.
    println!("{subject} {verb} {object}",
             object="the lazy dog",
             subject="the quick brown fox",
             verb="jumps over");

    // Different formatting can be invoked by specifying the format character
    // after a `:`.
    println!("Base 10:               {}",   69420); // 69420
    println!("Base 2 (binary):       {:b}", 69420); // 10000111100101100
    println!("Base 8 (octal):        {:o}", 69420); // 207454
    println!("Base 16 (hexadecimal): {:x}", 69420); // 10f2c

    // You can right-justify text with a specified width. This will
    // output "    1". (Four white spaces and a "1", for a total width of 5.)
    println!("{number:>5}", number=1);

    // You can pad numbers with extra zeroes,
    println!("{number:0>5}", number=1); // 00001
    // and left-adjust by flipping the sign. This will output "10000".
    println!("{number:0<5}", number=1); // 10000

    // You can use named arguments in the format specifier by appending a `$`.
    println!("{number:0>width$}", number=1, width=5);

    // Rust even checks to make sure the correct number of arguments are used.
    println!("My name is {0}, {1} {0}", "Bond");
    // FIXME ^ Add the missing argument: "James"

    // Only types that implement fmt::Display can be formatted with `{}`. User-
    // defined types do not implement fmt::Display by default.

    #[allow(dead_code)] // disable `dead_code` which warn against unused module
    struct Structure(i32);

    // This will not compile because `Structure` does not implement
    // fmt::Display.
    // println!("This struct `{}` won't print...", Structure(3));
    // TODO ^ Try uncommenting this line

    // For Rust 1.58 and above, you can directly capture the argument from a
    // surrounding variable. Just like the above, this will output
    // "    1", 4 white spaces and a "1".
    let number: f64 = 1.0;
    let width: usize = 5;
    println!("{number:>width$}");
}
```


Rust by Example › Formatted print

`std::fmt` contains many `traits` which govern the display
of text. The base form of two important ones are listed below:
* `fmt::Debug`: Uses the `{:?}` marker. Format text for debugging purposes.
* `fmt::Display`: Uses the `{}` marker. Format text in a more elegant, user
  friendly fashion.
Here, we used `fmt::Display` because the std library provides implementations
for these types. To print text for custom types, more steps are required.
Implementing the `fmt::Display` trait automatically implements the
[`ToString`] trait which allows us to [convert] the type to `String`.
In *line 43*, `#[allow(dead_code)]` is an [attribute] which only applies to the item after it.


Rust by Example › Formatted print › Activities

* Fix the issue in the above code (see FIXME) so that it runs without
  error.
* Try uncommenting the line that attempts to format the `Structure` struct
  (see TODO)
* Add a `println!` macro call that prints: `Pi is roughly 3.142` by controlling
  the number of decimal places shown. For the purposes of this exercise, use
  `let pi = 3.141592` as an estimate for pi. (Hint: you may need to check the
  `std::fmt` documentation for setting the number of decimals to display)


Rust by Example › Formatted print › See also:

`std::fmt`, `macros`, `struct`, `traits`, and `dead_code`


Rust by Example › Debug

All types which want to use `std::fmt` formatting `traits` require an
implementation to be printable. Automatic implementations are only provided
for types such as in the `std` library. All others *must* be manually
implemented somehow.
The `fmt::Debug` `trait` makes this very straightforward. *All* types can
`derive` (automatically create) the `fmt::Debug` implementation. This is
not true for `fmt::Display` which must be manually implemented.
```rust
// This structure cannot be printed either with `fmt::Display` or
// with `fmt::Debug`.
struct UnPrintable(i32);

// The `derive` attribute automatically creates the implementation
// required to make this `struct` printable with `fmt::Debug`.
#[derive(Debug)]
struct DebugPrintable(i32);
```
All `std` library types are automatically printable with `{:?}` too:
```rust,editable
// Derive the `fmt::Debug` implementation for `Structure`. `Structure`
// is a structure which contains a single `i32`.
#[derive(Debug)]
struct Structure(i32);

// Put a `Structure` inside of the structure `Deep`. Make it printable
// also.
#[derive(Debug)]
struct Deep(Structure);

fn main() {
    // Printing with `{:?}` is similar to with `{}`.
    println!("{:?} months in a year.", 12);
    println!("{1:?} {0:?} is the {actor:?} name.",
             "Slater",
             "Christian",
             actor="actor's");

    // `Structure` is printable!
    println!("Now {:?} will print!", Structure(3));

    // The problem with `derive` is there is no control over how
    // the results look. What if I want this to just show a `7`?
    println!("Now {:?} will print!", Deep(Structure(7)));
}
```


Rust by Example › Debug

So `fmt::Debug` definitely makes this printable but sacrifices some elegance.
Rust also provides "pretty printing" with `{:#?}`.
```rust,editable
#[derive(Debug)]
struct Person<'a> {
    name: &'a str,
    age: u8
}

fn main() {
    let name = "Peter";
    let age = 27;
    let peter = Person { name, age };

    // Pretty print
    println!("{:#?}", peter);
}
```
One can manually implement `fmt::Display` to control the display.


Rust by Example › Debug › See also:

`attributes`, `derive`, `std::fmt`,
and `struct`


Rust by Example › Display

`fmt::Debug` hardly looks compact and clean, so it is often advantageous to
customize the output appearance. This is done by manually implementing
`fmt::Display`, which uses the `{}` print marker. Implementing it
looks like this:
```rust
// Import (via `use`) the `fmt` module to make it available.
use std::fmt;

// Define a structure for which `fmt::Display` will be implemented. This is
// a tuple struct named `Structure` that contains an `i32`.
struct Structure(i32);

// To use the `{}` marker, the trait `fmt::Display` must be implemented
// manually for the type.
impl fmt::Display for Structure {
    // This trait requires `fmt` with this exact signature.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Write strictly the first element into the supplied output
        // stream: `f`. Returns `fmt::Result` which indicates whether the
        // operation succeeded or failed. Note that `write!` uses syntax which
        // is very similar to `println!`.
        write!(f, "{}", self.0)
    }
}
```
`fmt::Display` may be cleaner than `fmt::Debug` but this presents
a problem for the `std` library. How should ambiguous types be displayed?
For example, if the `std` library implemented a single style for all
`Vec<T>`, what style should it be? Would it be either of these two?
* `Vec<path>`: `/:/etc:/home/username:/bin` (split on `:`)
* `Vec<number>`: `1,2,3` (split on `,`)


Rust by Example › Display

No, because there is no ideal style for all types and the `std` library
doesn't presume to dictate one. `fmt::Display` is not implemented for `Vec<T>`
or for any other generic containers. `fmt::Debug` must then be used for these
generic cases.
This is not a problem though because for any new *container* type which is
*not* generic, `fmt::Display` can be implemented.


Rust by Example › Display

```rust,editable
use std::fmt; // Import `fmt`

// A structure holding two numbers. `Debug` will be derived so the results can
// be contrasted with `Display`.
#[derive(Debug)]
struct MinMax(i64, i64);

// Implement `Display` for `MinMax`.
impl fmt::Display for MinMax {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Use `self.number` to refer to each positional data point.
        write!(f, "({}, {})", self.0, self.1)
    }
}

// Define a structure where the fields are nameable for comparison.
#[derive(Debug)]
struct Point2D {
    x: f64,
    y: f64,
}

// Similarly, implement `Display` for `Point2D`.
impl fmt::Display for Point2D {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Customize so only `x` and `y` are denoted.
        write!(f, "x: {}, y: {}", self.x, self.y)
    }
}

fn main() {
    let minmax = MinMax(0, 14);

    println!("Compare structures:");
    println!("Display: {}", minmax);
    println!("Debug: {:?}", minmax);

    let big_range =   MinMax(-300, 300);
    let small_range = MinMax(-3, 3);

    println!("The big range is {big} and the small is {small}",
             small = small_range,
             big = big_range);

    let point = Point2D { x: 3.3, y: 7.2 };

    println!("Compare points:");
    println!("Display: {}", point);
    println!("Debug: {:?}", point);

    // The following line would not compile: both `Debug` and `Display`
    // were implemented, but `{:b}` requires `fmt::Binary` to be
    // implemented, which it hasn't been for `Point2D`.
    // println!("What does Point2D look like in binary: {:b}?", point);
}
```


Rust by Example › Display

So, `fmt::Display` has been implemented but `fmt::Binary` has not, and therefore
cannot be used. `std::fmt` has many such `traits` and each requires
its own implementation. This is detailed further in `std::fmt`.


Rust by Example › Display › Activity

After checking the output of the above example, use the `Point2D` struct as a
guide to add a `Complex` struct to the example. When printed in the same
way, the output should be:
```txt
Display: 3.3 +7.2i
Debug: Complex { real: 3.3, imag: 7.2 }

Display: 4.7 -2.3i
Debug: Complex { real: 4.7, imag: -2.3 }
```
Bonus: Add a space after the `+`/`-` signs.
Hints in case you get stuck:
- Check the documentation for `Sign/#/0` in `std::fmt`.
- Bonus: Check `if`-`else` branching and the `abs` function.


Rust by Example › Display › See also:

`derive`, `std::fmt`, `macros`, `struct`,
`trait`, and `use`


Rust by Example › Testcase: List

Implementing `fmt::Display` for a structure where the elements must each be
handled sequentially is tricky. The problem is that each `write!` generates a
`fmt::Result`. Proper handling of this requires dealing with *all* the
results. Rust provides the `?` operator for exactly this purpose.
Using `?` on `write!` looks like this:
```rust,ignore
// Try `write!` to see if it errors. If it errors, return
// the error. Otherwise continue.
write!(f, "{}", value)?;
```
With `?` available, implementing `fmt::Display` for a `Vec` is
straightforward:
```rust,editable
use std::fmt; // Import the `fmt` module.

// Define a structure named `List` containing a `Vec`.
struct List(Vec<i32>);

impl fmt::Display for List {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Create a reference to the Vec<i32> stored in the List struct.
        let vec = &self.0;

        write!(f, "[")?;

        // Iterate over `v` in `vec` while enumerating the iteration
        // index in `index`.
        for (index, v) in vec.iter().enumerate() {
            // For every element except the first, add a comma.
            // Use the ? operator to return on errors.
            if index != 0 { write!(f, ", ")?; }
            write!(f, "{}", v)?;
        }

        // Close the opened bracket and return a fmt::Result value.
        write!(f, "]")
    }
}

fn main() {
    let v = List(vec![1, 2, 3]);
    println!("{}", v);
}
```


Rust by Example › Testcase: List › Activity

Try changing the program so that the index of each element in the vector is also
printed. The new output should look like this:
```rust,ignore
[0: 1, 1: 2, 2: 3]
```


Rust by Example › Testcase: List › See also:

`for`, `ref`, `Result`, `struct`,
`?`, and `vec!`


Rust by Example › Formatting

We've seen that formatting is specified via a *format string*:
* `format!("{}", foo)` -> `"3735928559"`
* `format!("0x{:X}", foo)` -> `"0xDEADBEEF"`
* `format!("0o{:o}", foo)` -> `"0o33653337357"`
The same variable (`foo`) can be formatted differently depending on which
*argument type* is used: `X` vs `o` vs *unspecified*.
This formatting functionality is implemented via traits, and there is one trait
for each argument type. The most common formatting trait is `Display`, which
handles cases where the argument type is left unspecified: `{}` for instance.


Rust by Example › Formatting

```rust,editable
use std::fmt::{self, Formatter, Display};

struct City {
    name: &'static str,
    // Latitude
    lat: f32,
    // Longitude
    lon: f32,
}

impl Display for City {
    // `f` is a buffer, and this method must write the formatted string into it.
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };
        let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };

        // `write!` is like `format!`, but it will write the formatted string
        // into a buffer (the first argument).
        write!(f, "{}: {:.3}°{} {:.3}°{}",
               self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)
    }
}

#[derive(Debug)]
struct Color {
    red: u8,
    green: u8,
    blue: u8,
}

fn main() {
    for city in [
        City { name: "Dublin", lat: 53.347778, lon: -6.259722 },
        City { name: "Oslo", lat: 59.95, lon: 10.75 },
        City { name: "Vancouver", lat: 49.25, lon: -123.1 },
    ] {
        println!("{}", city);
    }
    for color in [
        Color { red: 128, green: 255, blue: 90 },
        Color { red: 0, green: 3, blue: 254 },
        Color { red: 0, green: 0, blue: 0 },
    ] {
        // Switch this to use {} once you've added an implementation
        // for fmt::Display.
        println!("{:?}", color);
    }
}
```


Rust by Example › Formatting

You can view a full list of formatting traits and their argument
types in the `std::fmt` documentation.


Rust by Example › Formatting › Activity

Add an implementation of the `fmt::Display` trait for the `Color` struct above
so that the output displays as:
```text
RGB (128, 255, 90) 0x80FF5A
RGB (0, 3, 254) 0x0003FE
RGB (0, 0, 0) 0x000000
```
Two hints if you get stuck:
* You may need to list each color more than once.
* You can pad with zeros to a width of 2 with `:0>2`.
For hexadecimals, you can use `:02X`.
Bonus:
* If you would like to experiment with type casting in advance,
the formula for calculating a color in the RGB color space is
`RGB = (R * 65_536) + (G * 256) + B`, where `R is RED, G is GREEN, and B is BLUE`.
An unsigned 8-bit integer (`u8`) can only hold numbers up to 255. To cast `u8` to `u32`, you can write `variable_name as u32`.


Rust by Example › Formatting › See also:

`std::fmt`


Rust by Example › Primitives

Rust provides access to a wide variety of `primitives`. A sample includes:


Rust by Example › Primitives › Scalar Types

* Signed integers: `i8`, `i16`, `i32`, `i64`, `i128` and `isize` (pointer size)
* Unsigned integers: `u8`, `u16`, `u32`, `u64`, `u128` and `usize` (pointer
  size)
* Floating point: `f32`, `f64`
* `char` Unicode scalar values like `'a'`, `'α'` and `'∞'` (4 bytes each)
* `bool` either `true` or `false`
* The unit type `()`, whose only possible value is an empty tuple: `()`
Despite the value of a unit type being a tuple, it is not considered a compound
type because it does not contain multiple values.


Rust by Example › Primitives › Compound Types

* Arrays like `[1, 2, 3]`
* Tuples like `(1, true)`
Variables can always be *type annotated*. Numbers may additionally be annotated
via a *suffix* or *by default*. Integers default to `i32` and floats to `f64`.
Note that Rust can also infer types from context.
```rust,editable,ignore,mdbook-runnable
fn main() {
    // Variables can be type annotated.
    let logical: bool = true;

    let a_float: f64 = 1.0;  // Regular annotation
    let an_integer   = 5i32; // Suffix annotation

    // Or a default will be used.
    let default_float   = 3.0; // `f64`
    let default_integer = 7;   // `i32`

    // A type can also be inferred from context.
    let mut inferred_type = 12; // Type i64 is inferred from another line.
    inferred_type = 4294967296i64;

    // A mutable variable's value can be changed.
    let mut mutable = 12; // Mutable `i32`
    mutable = 21;

    // Error! The type of a variable can't be changed.
    mutable = true;

    // Variables can be overwritten with shadowing.
    let mutable = true;

    /* Compound types - Array and Tuple */

    // Array signature consists of Type T and length as [T; length].
    let my_array: [i32; 5] = [1, 2, 3, 4, 5];

    // Tuple is a collection of values of different types
    // and is constructed using parentheses ().
    let my_tuple = (5u32, 1u8, true, -5.04f32);
}
```


Rust by Example › Primitives › See also:

the `std` library, `mut`, `inference`, and
`shadowing`


Rust by Example › Literals and operators

Integers `1`, floats `1.2`, characters `'a'`, strings `"abc"`, booleans `true`
and the unit type `()` can be expressed using literals.
Integers can, alternatively, be expressed using hexadecimal, octal or binary
notation using these prefixes respectively: `0x`, `0o` or `0b`.
Underscores can be inserted in numeric literals to improve readability, e.g.
`1_000` is the same as `1000`, and `0.000_001` is the same as `0.000001`.
Rust also supports scientific E-notation, e.g. `1e6`, `7.6e-4`. The
associated type is `f64`.
We need to tell the compiler the type of the literals we use. For now,
we'll use the `u32` suffix to indicate that the literal is an unsigned 32-bit
integer, and the `i32` suffix to indicate that it's a signed 32-bit integer.
The operators available and their precedence in Rust are similar
to other C-like languages.


Rust by Example › Literals and operators

```rust,editable
fn main() {
    // Integer addition
    println!("1 + 2 = {}", 1u32 + 2);

    // Integer subtraction
    println!("1 - 2 = {}", 1i32 - 2);
    // TODO ^ Try changing `1i32` to `1u32` to see why the type is important

    // Scientific notation
    println!("1e4 is {}, -2.5e-3 is {}", 1e4, -2.5e-3);

    // Short-circuiting boolean logic
    println!("true AND false is {}", true && false);
    println!("true OR false is {}", true || false);
    println!("NOT true is {}", !true);

    // Bitwise operations
    println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101);
    println!("0011 OR 0101 is {:04b}", 0b0011u32 | 0b0101);
    println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101);
    println!("1 << 5 is {}", 1u32 << 5);
    println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2);

    // Use underscores to improve readability!
    println!("One million is written as {}", 1_000_000u32);
}
```


Rust by Example › Tuples

A tuple is a collection of values of different types. Tuples are constructed
using parentheses `()`, and each tuple itself is a value with type signature
`(T1, T2, ...)`, where `T1`, `T2` are the types of its members. Functions can
use tuples to return multiple values, as tuples can hold any number of values.


Rust by Example › Tuples

```rust,editable
// Tuples can be used as function arguments and as return values.
fn reverse(pair: (i32, bool)) -> (bool, i32) {
    // `let` can be used to bind the members of a tuple to variables.
    let (int_param, bool_param) = pair;

    (bool_param, int_param)
}

// The following struct is for the activity.
#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);

fn main() {
    // A tuple with a bunch of different types.
    let long_tuple = (1u8, 2u16, 3u32, 4u64,
                      -1i8, -2i16, -3i32, -4i64,
                      0.1f32, 0.2f64,
                      'a', true);

    // Values can be extracted from the tuple using tuple indexing.
    println!("Long tuple first value: {}", long_tuple.0);
    println!("Long tuple second value: {}", long_tuple.1);

    // Tuples can be tuple members.
    let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);

    // Tuples are printable.
    println!("tuple of tuples: {:?}", tuple_of_tuples);

    // But long Tuples (more than 12 elements) cannot be printed.
    //let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
    //println!("Too long tuple: {:?}", too_long_tuple);
    // TODO ^ Uncomment the above 2 lines to see the compiler error

    let pair = (1, true);
    println!("Pair is {:?}", pair);

    println!("The reversed pair is {:?}", reverse(pair));

    // To create one element tuples, the comma is required to tell them apart
    // from a literal surrounded by parentheses.
    println!("One element tuple: {:?}", (5u32,));
    println!("Just an integer: {:?}", (5u32));

    // Tuples can be destructured to create bindings.
    let tuple = (1, "hello", 4.5, true);

    let (a, b, c, d) = tuple;
    println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);

    let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
    println!("{:?}", matrix);
}
```


Rust by Example › Tuples › Activity

1. *Recap*: Add the `fmt::Display` trait to the `Matrix` struct in the above
   example, so that if you switch from printing the debug format `{:?}` to the
   display format `{}`, you see the following output:
```text
   ( 1.1 1.2 )
   ( 2.1 2.2 )
```
   You may want to refer back to the example for print display.
2. Add a `transpose` function using the `reverse` function as a template, which
   accepts a matrix as an argument, and returns a matrix in which two elements
   have been swapped. For example:
```rust,ignore
   println!("Matrix:\n{}", matrix);
   println!("Transpose:\n{}", transpose(matrix));
```
   Results in the output:
```text
   Matrix:
   ( 1.1 1.2 )
   ( 2.1 2.2 )
   Transpose:
   ( 1.1 2.1 )
   ( 1.2 2.2 )
```


Rust by Example › Arrays and Slices

An array is a collection of objects of the same type `T`, stored in contiguous
memory. Arrays are created using brackets `[]`, and their length, which is known
at compile time, is part of their type signature `[T; length]`.
Slices are similar to arrays, but their length is not known at compile time.
Instead, a slice is a two-word object; the first word is a pointer to the data,
the second word is the length of the slice. The word size is the same as usize,
determined by the processor architecture, e.g. 64 bits on an x86-64. Slices can
be used to borrow a section of an array and have the type signature `&[T]`.


Rust by Example › Arrays and Slices

```rust,editable,ignore,mdbook-runnable
use std::mem;

// This function borrows a slice.
fn analyze_slice(slice: &[i32]) {
    println!("First element of the slice: {}", slice[0]);
    println!("The slice has {} elements", slice.len());
}

fn main() {
    // Fixed-size array (type signature is superfluous).
    let xs: [i32; 5] = [1, 2, 3, 4, 5];

    // All elements can be initialized to the same value.
    let ys: [i32; 500] = [0; 500];

    // Indexing starts at 0.
    println!("First element of the array: {}", xs[0]);
    println!("Second element of the array: {}", xs[1]);

    // `len` returns the count of elements in the array.
    println!("Number of elements in array: {}", xs.len());

    // Arrays are stack allocated.
    println!("Array occupies {} bytes", mem::size_of_val(&xs));

    // Arrays can be automatically borrowed as slices.
    println!("Borrow the whole array as a slice.");
    analyze_slice(&xs);

    // Slices can point to a section of an array.
    // They are of the form [starting_index..ending_index].
    // `starting_index` is the first position in the slice.
    // `ending_index` is one more than the last position in the slice.
    println!("Borrow a section of the array as a slice.");
    analyze_slice(&ys[1 .. 4]);

    // Example of empty slice `&[]`:
    let empty_array: [u32; 0] = [];
    assert_eq!(&empty_array, &[]);
    assert_eq!(&empty_array, &); // Same but more verbose

    // Arrays can be safely accessed using `.get`, which returns an
    // `Option`. This can be matched as shown below, or used with
    // `.expect()` if you would like the program to exit with a nice
    // message instead of happily continue.
    for i in 0..xs.len() + 1 { // Oops, one element too far!
        match xs.get(i) {
            Some(xval) => println!("{}: {}", i, xval),
            None => println!("Slow down! {} is too far!", i),
        }
    }

    // Out of bound indexing on array with constant value causes compile time error.
    //println!("{}", xs[5]);
    // Out of bound indexing on slice causes runtime error.
    //println!("{}", xs..);
}
```


Rust by Example › Custom Types

Rust custom data types are formed mainly through the two keywords:
* `struct`: define a structure
* `enum`: define an enumeration
Constants can also be created via the `const` and `static` keywords.


Rust by Example › Structures

There are three types of structures ("structs") that can be created using the
`struct` keyword:
* Tuple structs, which are, basically, named tuples.
* The classic C structs
* Unit structs, which are field-less, are useful for generics.