Add examples for some methods on slices

This commit is contained in:
Takashiidobe 2024-02-20 09:02:49 -05:00
parent cce6a6e22e
commit e59efe4d7e

View File

@ -146,6 +146,9 @@ pub const fn len(&self) -> usize {
/// ``` /// ```
/// let a = [1, 2, 3]; /// let a = [1, 2, 3];
/// assert!(!a.is_empty()); /// assert!(!a.is_empty());
///
/// let b: &[i32] = &[];
/// assert!(b.is_empty());
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")] #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")]
@ -185,6 +188,9 @@ pub const fn first(&self) -> Option<&T> {
/// *first = 5; /// *first = 5;
/// } /// }
/// assert_eq!(x, &[5, 1, 2]); /// assert_eq!(x, &[5, 1, 2]);
///
/// let y: &mut [i32] = &mut [];
/// assert_eq!(None, y.first_mut());
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
@ -297,7 +303,7 @@ pub const fn last(&self) -> Option<&T> {
if let [.., last] = self { Some(last) } else { None } if let [.., last] = self { Some(last) } else { None }
} }
/// Returns a mutable reference to the last item in the slice. /// Returns a mutable reference to the last item in the slice, or `None` if it is empty.
/// ///
/// # Examples /// # Examples
/// ///
@ -308,6 +314,9 @@ pub const fn last(&self) -> Option<&T> {
/// *last = 10; /// *last = 10;
/// } /// }
/// assert_eq!(x, &[0, 1, 10]); /// assert_eq!(x, &[0, 1, 10]);
///
/// let y: &mut [i32] = &mut [];
/// assert_eq!(None, y.last_mut());
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]