Skip to content

Commit a005b2c

Browse files
committed
Rewrite/expand doc examples for Vec::set_len.
1 parent 6aba7be commit a005b2c

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

src/libcollections/vec.rs

+30-2
Original file line numberDiff line numberDiff line change
@@ -532,9 +532,37 @@ impl<T> Vec<T> {
532532
/// # Examples
533533
///
534534
/// ```
535-
/// let mut v = vec![1, 2, 3, 4];
535+
/// use std::ptr;
536+
///
537+
/// let mut vec = vec!['r', 'u', 's', 't'];
538+
///
539+
/// unsafe {
540+
/// ptr::drop_in_place(&mut vec[3]);
541+
/// vec.set_len(3);
542+
/// }
543+
/// assert_eq!(vec, ['r', 'u', 's']);
544+
/// ```
545+
///
546+
/// In this example, there is a memory leak since the memory locations
547+
/// owned by the vector were not freed prior to the `set_len` call:
548+
///
549+
/// ```
550+
/// let mut vec = vec!['r', 'u', 's', 't'];
551+
///
552+
/// unsafe {
553+
/// vec.set_len(0);
554+
/// }
555+
/// ```
556+
///
557+
/// In this example, the vector gets expanded from zero to four items
558+
/// without any memory allocations occurring, resulting in vector
559+
/// values of unallocated memory:
560+
///
561+
/// ```
562+
/// let mut vec: Vec<char> = Vec::new();
563+
///
536564
/// unsafe {
537-
/// v.set_len(1);
565+
/// vec.set_len(4);
538566
/// }
539567
/// ```
540568
#[inline]

0 commit comments

Comments
 (0)