@@ -1624,8 +1624,71 @@ mod dyn_keyword {}
1624
1624
//
1625
1625
/// The [Rust equivalent of a C-style union][union].
1626
1626
///
1627
- /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
1627
+ /// A `union` looks like a [`struct`] in terms of declaration, but all of its
1628
+ /// fields exist simultaneously, superimposed over one another. For instance,
1629
+ /// if we wanted some bits in memory that we sometimes interpret as a `u32` and
1630
+ /// sometimes as an `f32`, we would write:
1631
+ ///
1632
+ /// ```rust
1633
+ /// union IntOrFloat {
1634
+ /// i: u32,
1635
+ /// f: f32,
1636
+ /// }
1637
+ ///
1638
+ /// let mut u = IntOrFloat { f: 1.0 };
1639
+ /// // Reading the fields of an union is always unsafe
1640
+ /// assert_eq!(unsafe { u.i }, 1065353216);
1641
+ /// // Updating through any of the field will modify all of them
1642
+ /// u.i = 1073741824;
1643
+ /// assert_eq!(unsafe { u.f }, 2.0);
1644
+ /// ```
1645
+ ///
1646
+ /// # Matching on unions
1647
+ ///
1648
+ /// It is possible to use pattern matching on `union`s. A single field name must
1649
+ /// be used and it must match the name of one of the `union`'s field.
1650
+ ///
1651
+ /// ```rust
1652
+ /// union IntOrFloat {
1653
+ /// i: u32,
1654
+ /// f: f32,
1655
+ /// }
1656
+ ///
1657
+ /// let u = IntOrFloat { f: 1.0 };
1658
+ ///
1659
+ /// unsafe {
1660
+ /// match u {
1661
+ /// IntOrFloat { i: 10 } => println!("Found exactly ten !"),
1662
+ /// // The field name is used to deduce the type
1663
+ /// IntOrFloat { f } => println!("Found f = {} !", f),
1664
+ /// }
1665
+ /// }
1666
+ /// ```
1667
+ ///
1668
+ /// # References to union fields
1669
+ ///
1670
+ /// All fields in a union are all at the same place in memory which means
1671
+ /// borrowing one borrows all of them, for the same duration:
1672
+ ///
1673
+ /// ```rust,compile_fail,E0502
1674
+ /// union IntOrFloat {
1675
+ /// i: u32,
1676
+ /// f: f32,
1677
+ /// }
1628
1678
///
1679
+ /// let mut u = IntOrFloat { f: 1.0 };
1680
+ ///
1681
+ /// let f = unsafe { &u.f };
1682
+ /// // This will not compile because the field has already been borrowed, even
1683
+ /// // if only immutably
1684
+ /// let i = unsafe { &mut u.i };
1685
+ ///
1686
+ /// *i = 10;
1687
+ /// println!("f = {} and i = {}", f, i);
1688
+ /// ```
1689
+ ///
1690
+ /// See the [Reference][union] for more informations on `union`s.
1691
+ ///
1692
+ /// [`struct`]: keyword.struct.html
1629
1693
/// [union]: ../reference/items/unions.html
1630
- /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1631
1694
mod union_keyword { }
0 commit comments