User Tools

Site Tools


Rust OOP sample

sample.rs
/*
 * Author, Copyright: Oleg Borodin <onborodin@gmail.com>
 */
 
 
#[derive(Debug, Copy, Clone, Default)]
struct Point {
    x: i32,
    y: i32
}
 
//impl Default for Point{
//    fn default() -> Point {
//        Point {
//            x: 2,
//            y: 4
//        }
//    }
//}
 
impl Point {
    #[allow(dead_code)]
    fn new(x: i32, y: i32) -> Point {
        Point { x: x, y: y }
    }
    fn default() -> Point {
        Point { ..Default::default() }
    }
    fn set(&mut self, x: i32, y: i32) -> &mut Point {
        self.x = x;
        self.y = y;
        self
    }
}
#[derive(Debug, Clone, Default)]
struct Person {
    name: String,
    age: i32
}
 
fn main() {
    let mut point = Point::default();
    point.set(3,4).set(5, 6);
    println!("point: {} {}", point.x, point.y);
    println!("{:#?}", point);
 
    let man = Person { name: String::from("John"), age: 34 };
    println!("{:#?}", man);
}

Out

$ rustc main.rs 
$ ./main
point: 5 6
Point {
    x: 5,
    y: 6,
}
Person {
    name: "John",
    age: 34,
}