indexing - Implementing Index trait to return a value that is not a reference -
i have simple struct implement index
for, newcomer rust i'm having number of troubles borrow checker. struct pretty simple, i'd have store start , step value, when indexed usize
should return start + idx * step
:
pub struct mystruct { pub start: f64, pub step: f64, }
my intuition i'd able take signature of index
, plug in types:
impl index<usize> mystruct { type output = f64; fn index(&self, idx: usize) -> &f64 { self.start + (idx f64) * self.step } }
this gives error mismatched types
saying expected type &f64, found type f64
. has yet understand how rust's type system works, tried slapping &
on expression:
fn index(&self, idx: usize) -> &f64 { &(self.start + (idx f64) * self.step) }
this tells me borrowed value not live long enough
, maybe needs lifetime variable?
fn index<'a>(&self, idx: usize) -> &'a f64 { &(self.start + (idx f64) * self.step) }
the error same, note gives lifetime 'a
instead of lifetime #1
, guess that's not necessary, @ point feel i'm stuck. i'm confused such simple exercise languages has become difficult implement in rust, since want return computation function happens behind reference. how should go implementing index
simple structure value calculated on demand?
the index
trait meant return borrowed pointer member of self
(e.g. item in vec
). signature of index
method index
trait makes impractical implement have behavior described, you'd have store every value returned index
in self
, ensure pointers remain valid until mystruct
dropped.
Comments
Post a Comment