-
-
Save allwelldotdev/10630be265c9548bfb0c591767afedf2 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Creating a heapless vector type (useful in embedded systems where there's | |
| // limited memory space for heap allocations) | |
| #[derive(Debug)] | |
| struct ArrayVec<T, const N: usize> | |
| where | |
| T: Copy | |
| { | |
| values: [Option<T>; N], | |
| len: usize, | |
| } | |
| impl<T, const N: usize> ArrayVec<T, N> | |
| where | |
| T: Copy | |
| { | |
| fn new() -> Self { | |
| ArrayVec { | |
| values: [None; N], | |
| len: 0, | |
| } | |
| } | |
| fn try_push(&mut self, t: T) -> Result<(), T> { | |
| if self.len == N { | |
| return Err(t); | |
| } | |
| self.values[self.len] = Some(t); | |
| self.len += 1; | |
| Ok(()) | |
| } | |
| } | |
| const SIZE: usize = 5; | |
| fn main() { | |
| let mut arr_vec1 = ArrayVec::<i32, SIZE>::new(); | |
| println!("{:?}", arr_vec1); // view ArrayVec after init | |
| let mut count = 0; | |
| for i in 0..SIZE { | |
| count = 10 + i as i32; | |
| arr_vec1.try_push(count).unwrap(); | |
| } | |
| println!("{:?}", arr_vec1); // view ArrayVec after pushing elements | |
| // Pushing elements beyond ArrayVec len; should return Err | |
| let err = arr_vec1.try_push(count + 1); | |
| println!("{:?}", err); | |
| // arr_vec does not change | |
| println!("{:?}", arr_vec1); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment