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