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:
add layer of
option
ness, returningoption<&option<foo>>
. i’m guessing don’t want this.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, } }
store suitable
none
static , return reference it. lifetime'static
(so longfoo
'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
Post a Comment