rust - "cannot move out borrowed content" when assigning a variable from a struct field -


i'm learning rust , i'm fighting against borrow checker.

i have basic point structure. have scale function modifies coordinates of point. call method method named convert:

fn factor(from: angleunit, to: angleunit) -> f32 {}  impl point {     pub fn new(x: f32, y: f32, z: f32, unit: angleunit) -> point {         point { x: x, y: y, z: z, unit: unit }     }      fn scale(&mut self, factor: f32) {         self.x = self.x * factor;         self.y = self.y * factor;         self.z = self.z * factor;     }      fn convert(&mut self, unit: angleunit) {         let pointunit = self.unit;         self.scale(factor(pointunit, unit));     } } 

but have following error:

cannot move out borrowed content 

what doing wrong?

the complete error message states:

error: cannot move out of borrowed content [e0507]     let pointunit = self.unit;                     ^~~~  note: attempting move value here     let pointunit = self.unit;         ^~~~~~~~~  help: prevent move, use `ref pointunit` or `ref mut pointunit`       capture value reference 

which useful understand move occurring. unfortunately, doesn't cover want do.

the simplest solution implement either copy or clone angleunit type. if it's copy, code work as-is. if it's clone, have explicitly call .clone() make duplicate.

if type cannot made `copy, can use references. if try this, need reorder code bit in order avoid outstanding borrow in function arguments (a limitation of current borrow checker implementation):

fn factor(from: &angleunit, to: &angleunit) -> f32 { 1.0 }  fn convert(&mut self, unit: angleunit) {     let factor = factor(&self.unit, &unit);     self.scale(factor); } 

the original problem boils down line:

let pointunit = self.unit; 

what should value of pointunit be?

if moved value self.unit pointunit, value of self.unit be? "easy" solution undefined memory, experience has shown programmers screw , introduce exciting-to-debug problems.

we copy value automatically, happen if angleunit type took 10 mib of space? innocent looking line sucked bunch of memory , time. that's not nice either.

instead, rust makes types moved default , cannot leave object in undefined state. types can opt ability automatically copied — copy trait. can allow types explicitly copied — clone trait. can obtain reference existing value , pass around. borrow checker prevent using reference after no longer valid.


as aside, rust style use camel_case identifiers methods , variables. variable should called point_unit.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -