How to share functionality in Rust? -


struct vector {     data: [f32; 2] }  impl vector {    //many methods } 

now want create normal behave vector need differentiate type. because example transforming normal different transforming vector. need transform tranposed(inverse) matrix example.

now this:

struct normal {     v: vector } 

and reimplement functionality

impl normal {     fn dot(self, other: normal) -> f32 {         vector::dot(self.v, other.v)     }     .... } 

i think phantomdata

struct vectortype; struct normaltype; struct pointtype; struct vector<t = vectortype> {     data: [f32; 2],     _type: phantomdata<t>, } type normal = vector<normaltype>; 

but need way implement functionality specific types.

it should easy implement example add possible add point + vector.

or functionality specific type

impl vector<normaltype> {..} // normal specific stuff 

not sure how implement functionality subrange. example maybe dot product makes sense normals , vectors not points.

is possible express boolean expression trait bounds?

trait normaltrait; trait vectortrait; impl normaltrait normaltype {} impl vectortrait vectortype {}  impl<t: pointtrait or vectortrait> vector<t> {     fn dot(self, other: vector<t>) -> f32 {..}  } 

what alternatives?

your question pretty broad , touches many topics. phantomdata idea solution. can write different impl blocks different generic types. added few things code:

struct vectortype; struct normaltype; struct pointtype; struct vector<t = vectortype> {     data: [f32; 2],     _type: phantomdata<t>, } type normal = vector<normaltype>; type point = vector<pointtype>;  // --- above line old code --------------------  trait pointy {} impl pointy vectortype {} impl pointy pointtype {}  // implement vector types impl<t> vector<t> {     fn new() -> self {         vector {             data: [0.0, 0.0],             _type: phantomdata,         }     } }  // impl 'pointy' vector types impl<t: pointy> vector<t> {     fn add<r>(&mut self, other: vector<r>) {}     fn transform(&mut self) { /* standard matrix multiplication */ } }  // impl normals impl vector<normaltype> {     fn transform(&mut self) { /* tranposed inversed matrix stuff */ } }  fn main() {     let mut n = normal::new();     let mut p = point::new();     n.transform();     p.transform();      // n.add(normal::new());  // error:     // no method named `add` found type `vector<normaltype>` in current scope     p.add(point::new()); } 

is possible express boolean expression trait bounds?

no (not yet). can solve in case shown above: create new trait (pointy) , implement types in "or"-condition. bound trait.


Comments

Popular posts from this blog

matlab - error with cyclic autocorrelation function -

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

c# - What is a good .Net RefEdit control to use with ExcelDna? -