Skip to content

Commit

Permalink
Rollup merge of rust-lang#73867 - poliorcetics:union-keyword, r=josht…
Browse files Browse the repository at this point in the history
…riplett

Document the union keyword

Partial fix of rust-lang#34601.

This documents the `union` keyword by presenting three cases: simply using a union, matching on a union and referencing the fields of a union.

@rustbot modify labels: T-doc,C-enhancement
  • Loading branch information
Manishearth committed Jul 13, 2020
2 parents 2481ade + 614f773 commit 0663d5e
Showing 1 changed file with 66 additions and 2 deletions.
68 changes: 66 additions & 2 deletions src/libstd/keyword_docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1732,8 +1732,72 @@ mod dyn_keyword {}
//
/// The [Rust equivalent of a C-style union][union].
///
/// The documentation for this keyword is [not yet complete]. Pull requests welcome!
/// A `union` looks like a [`struct`] in terms of declaration, but all of its
/// fields exist in the same memory, superimposed over one another. For instance,
/// if we wanted some bits in memory that we sometimes interpret as a `u32` and
/// sometimes as an `f32`, we could write:
///
/// ```rust
/// union IntOrFloat {
/// i: u32,
/// f: f32,
/// }
///
/// let mut u = IntOrFloat { f: 1.0 };
/// // Reading the fields of an union is always unsafe
/// assert_eq!(unsafe { u.i }, 1065353216);
/// // Updating through any of the field will modify all of them
/// u.i = 1073741824;
/// assert_eq!(unsafe { u.f }, 2.0);
/// ```
///
/// # Matching on unions
///
/// It is possible to use pattern matching on `union`s. A single field name must
/// be used and it must match the name of one of the `union`'s field.
/// Like reading from a `union`, pattern matching on a `union` requires `unsafe`.
///
/// ```rust
/// union IntOrFloat {
/// i: u32,
/// f: f32,
/// }
///
/// let u = IntOrFloat { f: 1.0 };
///
/// unsafe {
/// match u {
/// IntOrFloat { i: 10 } => println!("Found exactly ten!"),
/// // Matching the field `f` provides an `f32`.
/// IntOrFloat { f } => println!("Found f = {} !", f),
/// }
/// }
/// ```
///
/// # References to union fields
///
/// All fields in a `union` are all at the same place in memory which means
/// borrowing one borrows the entire `union`, for the same lifetime:
///
/// ```rust,compile_fail,E0502
/// union IntOrFloat {
/// i: u32,
/// f: f32,
/// }
///
/// let mut u = IntOrFloat { f: 1.0 };
///
/// let f = unsafe { &u.f };
/// // This will not compile because the field has already been borrowed, even
/// // if only immutably
/// let i = unsafe { &mut u.i };
///
/// *i = 10;
/// println!("f = {} and i = {}", f, i);
/// ```
///
/// See the [Reference][union] for more informations on `union`s.
///
/// [`struct`]: keyword.struct.html
/// [union]: ../reference/items/unions.html
/// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
mod union_keyword {}

0 comments on commit 0663d5e

Please sign in to comment.