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> {
394394 T :: from_variant ( variant)
395395 }
396396
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+
397409 /// Returns the first element in the array, or `None` if the array is empty. Equivalent of
398410 /// `front()` in GDScript.
399411 pub fn first ( & self ) -> Option < T > {
Original file line number Diff line number Diff line change @@ -167,6 +167,15 @@ fn array_get() {
167167 } ) ;
168168}
169169
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+
170179#[ itest]
171180fn array_first_last ( ) {
172181 let array = array ! [ 1 , 2 ] ;
You can’t perform that action at this time.
0 commit comments