@@ -280,6 +280,66 @@ where
280
280
}
281
281
}
282
282
283
+ /// Returns a reference to the last element of the array, or `None` if it
284
+ /// is empty.
285
+ ///
286
+ /// # Example
287
+ ///
288
+ /// ```rust
289
+ /// use ndarray::Array3;
290
+ ///
291
+ /// let mut a = Array3::<f64>::zeros([3, 4, 2]);
292
+ /// a[[2, 3, 1]] = 42.;
293
+ /// assert_eq!(a.last(), Some(&42.));
294
+ ///
295
+ /// let b = Array3::<f64>::zeros([3, 0, 5]);
296
+ /// assert_eq!(b.last(), None);
297
+ /// ```
298
+ pub fn last ( & self ) -> Option < & A >
299
+ where
300
+ S : Data ,
301
+ {
302
+ if self . is_empty ( ) {
303
+ None
304
+ } else {
305
+ let mut index = self . raw_dim ( ) ;
306
+ for ax in 0 ..index. ndim ( ) {
307
+ index[ ax] -= 1 ;
308
+ }
309
+ Some ( unsafe { self . uget ( index) } )
310
+ }
311
+ }
312
+
313
+ /// Returns a mutable reference to the last element of the array, or `None`
314
+ /// if it is empty.
315
+ ///
316
+ /// # Example
317
+ ///
318
+ /// ```rust
319
+ /// use ndarray::Array3;
320
+ ///
321
+ /// let mut a = Array3::<f64>::zeros([3, 4, 2]);
322
+ /// *a.last_mut().unwrap() = 42.;
323
+ /// assert_eq!(a[[2, 3, 1]], 42.);
324
+ ///
325
+ /// let mut b = Array3::<f64>::zeros([3, 0, 5]);
326
+ /// assert_eq!(b.last_mut(), None);
327
+ /// ```
328
+ pub fn last_mut ( & mut self ) -> Option < & mut A >
329
+ where
330
+ S : DataMut ,
331
+ {
332
+ if self . is_empty ( ) {
333
+ None
334
+ } else {
335
+ let mut index = self . raw_dim ( ) ;
336
+ for ax in 0 ..index. ndim ( ) {
337
+ index[ ax] -= 1 ;
338
+ }
339
+ Some ( unsafe { self . uget_mut ( index) } )
340
+ }
341
+ }
342
+
283
343
/// Return an iterator of references to the elements of the array.
284
344
///
285
345
/// Elements are visited in the *logical order* of the array, which
0 commit comments