Vec<u8>::get return Option<u8> instead?

  1. I am aware of mod.rs - source , which returns Optionn<&u8>.

  2. I understand how this is the right solution in the general case since we might not have T::Copy or T::Clone, and even if we did, it might be cheaper to just return a ref.

  3. However, for the u8 case, I'd really prefer it return a Option instead. Is there a simple way to transform Option<&u8> to Option ?

2 Likes

I'm sorry, do you want a method like this (In pseudorust):

impl<T> Vec<T> {
    pub fn get(&self, ind: impl Index) -> T;
}

or like this:

impl<T> Vec<T> {
    pub fn get(&self, ind: impl Index) -> Option<T>;
}

The first one is called indexing, ie my_vec[ind] and will panic in the case that it doesn't succeed.
The second one doesn't implicitly exist, but as @Hyeonu said, .cloned will work.


Ah, I just realized why the confusion, when you type the following without code formatting backticks (`):

Option<u8> 

you instead get Option because <u8> is going to be considered an html tag.

2 Likes
  1. @Hyeonu 's solution solved my problem.

  2. @OptimisticPeach : Sorry about the confusion, I didn't reailze some of the Option<u8> showed up as OPtion.