@@ -479,18 +479,45 @@ impl<T> Vec<T> {
479
479
}
480
480
}
481
481
482
- /// Shorten a vector to be `len` elements long, dropping excess elements.
482
+ /// Shortens the vector, keeping the first `len` elements and dropping
483
+ /// the rest.
483
484
///
484
485
/// If `len` is greater than the vector's current length, this has no
485
486
/// effect.
486
487
///
488
+ /// The [`drain`] method can emulate `truncate`, but causes the excess
489
+ /// elements to be returned instead of dropped.
490
+ ///
487
491
/// # Examples
488
492
///
493
+ /// Truncating a five element vector to two elements:
494
+ ///
489
495
/// ```
490
496
/// let mut vec = vec![1, 2, 3, 4, 5];
491
497
/// vec.truncate(2);
492
498
/// assert_eq!(vec, [1, 2]);
493
499
/// ```
500
+ ///
501
+ /// No truncation occurs when `len` is greater than the vector's current
502
+ /// length:
503
+ ///
504
+ /// ```
505
+ /// let mut vec = vec![1, 2, 3];
506
+ /// vec.truncate(8);
507
+ /// assert_eq!(vec, [1, 2, 3]);
508
+ /// ```
509
+ ///
510
+ /// Truncating when `len == 0` is equivalent to calling the [`clear`]
511
+ /// method.
512
+ ///
513
+ /// ```
514
+ /// let mut vec = vec![1, 2, 3];
515
+ /// vec.truncate(0);
516
+ /// assert_eq!(vec, []);
517
+ /// ```
518
+ ///
519
+ /// [`clear`]: #method.clear
520
+ /// [`drain`]: #method.drain
494
521
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
495
522
pub fn truncate ( & mut self , len : usize ) {
496
523
unsafe {
0 commit comments