rust - How can I return None from a function that borrows from it's argument, or avoid needing to? -


i have slice of option, , given value, if value valid index in slice want use value @ index, otherwise use none.

now, values need able reused, think want borrow slice, not move... note foo not implement copy trait , i'd prefer keep way.

i need often, function returning &option<foo> seemed appropriate, addition of lifetime specifier since return value shouldn't outlive slice borrowed from. leads me to:

fn get_or_none<'a>(data: &'a [option<foo>], bar: u8) -> &'a option<foo> {   match bar usize {     idx if idx < data.len() => &data[idx],     _ => &none // can't work   } } 

this wrong. can cheat, now, because know particular application first value in slice none (it's property of data, speak), that's avoiding problem.

what should instead?

there few approaches take:

  1. add layer of optionness, returning option<&option<foo>>. i’m guessing don’t want this.

  2. return option<&foo> instead of &option<foo>:

    fn get_or_none(data: &[option<foo>], bar: u8) -> option<&foo> {     match data.get(bar usize) {         some(&some(ref foo)) => some(foo),         _ => none,     } } 
  3. store suitable none static , return reference it. lifetime 'static (so long foo 'static), reference can shortened 'a no problems.

    static no_foo: option<foo> = none;  fn get_or_none(data: &[option<foo>], bar: u8) -> &option<foo> {     data.get(bar usize).unwrap_or(&no_foo) } 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -