Skip to content

Document the union keyword #73867

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 14, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 65 additions & 2 deletions src/libstd/keyword_docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1624,8 +1624,71 @@ 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 simultaneously, 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 would 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.
///
/// ```rust
/// union IntOrFloat {
/// i: u32,
/// f: f32,
/// }
///
/// let u = IntOrFloat { f: 1.0 };
///
/// unsafe {
/// match u {
/// IntOrFloat { i: 10 } => println!("Found exactly ten !"),
/// // The field name is used to deduce the type
/// 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 all of them, for the same duration:
///
/// ```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 {}