struct Point {
x: f64,
y: f64,
}
impl Point {
// associated function
// generally used as constructor
fn origin() -> Point {
Point { x: 0.0, y: 0.0 }
}
// another associated function
fn new(x: f64, y: f64) -> Point {
Point { x: x, y: y}
}
// immutable method
fn print(&self) {
println!("Point(x={}, y={})", self.x, self.y);
}
// mutable method
fn set(&mut self, x: f64, y: f64) {
self.x = x;
self.y = y;
}
}
fn main() {
// create an immutable instance
// using 'The One True Constructor'
let p1 = Point { x: 1.0, y: 2.5 };
p1.print();
// and a mutable instance
let mut p2 = Point { x: 0.3, y: 3.3 };
p2.print();
p2.set(1.0, 2.0);
p2.print();
// using associated function as constructor
let p3 = Point::origin();
p3.print();
// using another associated function
let p4 = Point::new(3.4, 4.3);
p4.print();
}
To embed this project on your website, copy the following code and paste it into your website's HTML: