How can I make this code work? (More advanced example from tutorial)


#1

Hello,
Recently, I’ve been looking into Rust, and I liked it. So I started following the tutorial and I tried to combine things. I made an Enum for a triangular shape and ractangular shape and used it to construct the geometry object. However, I get two errors while compiling, Cannot move out of borrowed content Here’ s my code:

enum Area {
	Radius(f64),
	WidthAndHeight(f64, f64),
}

struct GeometryBuilder {
	x: f64,
	y: f64,
	area: Area,
}
struct Geometry {
	x: f64,
	y: f64,
	area: Area,
}

impl Geometry {
	fn area(&self) -> f64 {
		match self.area {
			Area::Radius(o) => std::f64::consts::PI * o * o,
			Area::WidthAndHeight(w, h) => w * h
		}
	}
}

impl GeometryBuilder {
	fn new(object: Area) -> GeometryBuilder {
		match object {
			o @ Area::Radius(..) => GeometryBuilder{x: 0.0, y: 0.0, area: o},
			o @ Area::WidthAndHeight(..) => GeometryBuilder{x: 0.0, y: 0.0, area: o}
		}
	}
	fn y(&mut self, y: f64) -> &mut GeometryBuilder {
		self.y = y;
		self
	}
	fn x(&mut self, x: f64) -> &mut GeometryBuilder {
		self.x = x;
		self
	}
	fn finalise(self) -> Geometry {
		let area = self.area;
		Geometry {x: self.x, y: self.y, area: area}
	}
}

fn main(){
	let circle = GeometryBuilder::new(Area::Radius(2.0)).y(2.0).x(2.0).finalise();
	let area = circle.area();
}

I’m sorry if this is an obvious thing, but I’m new to rust and I don’t know everything from the language.
Many thanks.


#2

Hi,

There are two problems with this code. Here is a working example

https://play.rust-lang.org/?gist=c8dd792bf1c11ecac0c8&version=stable

fn finalise(self) -> Geometry {
    let area = self.area;
    Geometry {x: self.x, y: self.y, area: area}
}

This needs to be changed to (notice the declaration of self)

fn finalise(&self) -> Geometry {
    let area = self.area;
    Geometry {x: self.x, y: self.y, area: area}
}

Another problem is that Area enum can’t be copied by default. You can solve this by changing it to

#[derive(Clone, Copy)]
enum Area {
    Radius(f64),
    WidthAndHeight(f64, f64),
}

Hope this helps.

Cheers!


#3

Many thanks! It works!