Skip to content

Commit 27876c0

Browse files
Rollup merge of rust-lang#34911 - frewsxcv:vec-set-len, r=steveklabnik
Rewrite/expand doc examples for `Vec::set_len`. None
2 parents 91fd838 + a005b2c commit 27876c0

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

src/libcollections/vec.rs

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -565,9 +565,37 @@ impl<T> Vec<T> {
565565
/// # Examples
566566
///
567567
/// ```
568-
/// let mut v = vec![1, 2, 3, 4];
568+
/// use std::ptr;
569+
///
570+
/// let mut vec = vec!['r', 'u', 's', 't'];
571+
///
572+
/// unsafe {
573+
/// ptr::drop_in_place(&mut vec[3]);
574+
/// vec.set_len(3);
575+
/// }
576+
/// assert_eq!(vec, ['r', 'u', 's']);
577+
/// ```
578+
///
579+
/// In this example, there is a memory leak since the memory locations
580+
/// owned by the vector were not freed prior to the `set_len` call:
581+
///
582+
/// ```
583+
/// let mut vec = vec!['r', 'u', 's', 't'];
584+
///
585+
/// unsafe {
586+
/// vec.set_len(0);
587+
/// }
588+
/// ```
589+
///
590+
/// In this example, the vector gets expanded from zero to four items
591+
/// without any memory allocations occurring, resulting in vector
592+
/// values of unallocated memory:
593+
///
594+
/// ```
595+
/// let mut vec: Vec<char> = Vec::new();
596+
///
569597
/// unsafe {
570-
/// v.set_len(1);
598+
/// vec.set_len(4);
571599
/// }
572600
/// ```
573601
#[inline]

0 commit comments

Comments
 (0)