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 @@ -394,6 +394,18 @@ impl<T: GodotType + FromGodot> Array<T> {
394
394
T :: from_variant ( variant)
395
395
}
396
396
397
+ /// Returns the value at the specified index or `None` if the index is out-of-bounds.
398
+ pub fn try_get ( & self , index : usize ) -> Option < T > {
399
+ let ptr = self . ptr_or_null ( index) ;
400
+ if ptr. is_null ( ) {
401
+ None
402
+ } else {
403
+ // SAFETY: `ptr.is_null()` just verified that the index is not out of bounds.
404
+ let variant = unsafe { & * ptr } ;
405
+ Some ( T :: from_variant ( variant) )
406
+ }
407
+ }
408
+
397
409
/// Returns the first element in the array, or `None` if the array is empty. Equivalent of
398
410
/// `front()` in GDScript.
399
411
pub fn first ( & self ) -> Option < T > {
Original file line number Diff line number Diff line change @@ -167,6 +167,15 @@ fn array_get() {
167
167
} ) ;
168
168
}
169
169
170
+ #[ itest]
171
+ fn array_try_get ( ) {
172
+ let array = array ! [ 1 , 2 ] ;
173
+
174
+ assert_eq ! ( array. try_get( 0 ) , Some ( 1 ) ) ;
175
+ assert_eq ! ( array. try_get( 1 ) , Some ( 2 ) ) ;
176
+ assert_eq ! ( array. try_get( 2 ) , None ) ;
177
+ }
178
+
170
179
#[ itest]
171
180
fn array_first_last ( ) {
172
181
let array = array ! [ 1 , 2 ] ;
You can’t perform that action at this time.
0 commit comments