File tree Expand file tree Collapse file tree 2 files changed +21
-0
lines changed
itest/rust/src/builtin_tests/containers Expand file tree Collapse file tree 2 files changed +21
-0
lines changed Original file line number Diff line number Diff line change @@ -404,6 +404,18 @@ impl<T: GodotType + FromGodot> Array<T> {
404
404
T :: from_variant ( variant)
405
405
}
406
406
407
+ /// Returns the value at the specified index or `None` if the index is out-of-bounds.
408
+ pub fn try_get ( & self , index : usize ) -> Option < T > {
409
+ let ptr = self . ptr_or_null ( index) ;
410
+ if ptr. is_null ( ) {
411
+ None
412
+ } else {
413
+ // SAFETY: `ptr.is_null()` just verified that the index is not out of bounds.
414
+ let variant = unsafe { & * ptr } ;
415
+ Some ( T :: from_variant ( variant) )
416
+ }
417
+ }
418
+
407
419
/// Returns the first element in the array, or `None` if the array is empty. Equivalent of
408
420
/// `front()` in GDScript.
409
421
pub fn first ( & self ) -> Option < T > {
Original file line number Diff line number Diff line change @@ -168,6 +168,15 @@ fn array_get() {
168
168
} ) ;
169
169
}
170
170
171
+ #[ itest]
172
+ fn array_try_get ( ) {
173
+ let array = array ! [ 1 , 2 ] ;
174
+
175
+ assert_eq ! ( array. try_get( 0 ) , Some ( 1 ) ) ;
176
+ assert_eq ! ( array. try_get( 1 ) , Some ( 2 ) ) ;
177
+ assert_eq ! ( array. try_get( 2 ) , None ) ;
178
+ }
179
+
171
180
#[ itest]
172
181
fn array_first_last ( ) {
173
182
let array = array ! [ 1 , 2 ] ;
You can’t perform that action at this time.
0 commit comments