Skip to content

Commit 149aab8

Browse files
author
balt-dev
committed
Update example on push_mut
1 parent 6a69760 commit 149aab8

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

library/alloc/src/vec/mod.rs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2514,11 +2514,28 @@ impl<T, A: Allocator> Vec<T, A> {
25142514
/// ```
25152515
/// #![feature(push_mut)]
25162516
///
2517-
/// let mut vec = vec![];
2518-
/// // Due to current borrow checker limitations (see -Zpolonius), this is the only way to spell this right now.
2519-
/// let last = if let Some(v) = vec.last_mut() { v } else { vec.push_mut(0) };
2520-
/// *last += 6;
2521-
/// assert_eq!(vec, [6]);
2517+
/// # #[allow(unused)]
2518+
/// #[derive(PartialEq, Eq, Debug)]
2519+
/// struct Item { identifier: &'static str, count: usize }
2520+
///
2521+
/// impl Default for Item {
2522+
/// fn default() -> Self {
2523+
/// return Self { identifier: "stone", count: 64 }
2524+
/// }
2525+
/// }
2526+
///
2527+
/// let mut items = vec![];
2528+
///
2529+
/// // We can mutate the just-pushed value without having to fetch it again
2530+
/// for count in [15, 35, 61] {
2531+
/// let item = items.push_mut(Item::default());
2532+
/// item.count = count;
2533+
/// }
2534+
///
2535+
/// assert_eq!(
2536+
/// items,
2537+
/// [Item { identifier: "stone", count: 15 }, Item { identifier: "stone", count: 35 }, Item { identifier: "stone", count: 61 }]
2538+
/// );
25222539
/// ```
25232540
///
25242541
/// # Time complexity
@@ -2563,8 +2580,12 @@ impl<T, A: Allocator> Vec<T, A> {
25632580
///
25642581
/// Takes *O*(1) time.
25652582
#[inline]
2583+
2584+
// Since there's currently no way to have multiple unstable attributes on the same item, I compromised.
2585+
// Uncomment/delete the respective attribute when its respective issue stabilizes, since this falls under both.
25662586
#[unstable(feature = "push_mut", issue = "135974")]
25672587
// #[unstable(feature = "vec_push_within_capacity", issue = "100486")]
2588+
25682589
#[must_use = "if you don't need a reference to the value, use Vec::push_within_capacity instead"]
25692590
pub fn push_mut_within_capacity(&mut self, value: T) -> Result<&mut T, T> {
25702591
if self.len == self.buf.capacity() {

0 commit comments

Comments
 (0)