Skip to content

Commit 8ddc133

Browse files
committed
added point example
1 parent d5436a2 commit 8ddc133

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,4 @@ in a controlled repository now.
1616
* `readline`: example of readline with error handling
1717
* `error`: example of creating a custom error
1818
* `modules`: example of Rust modules
19+
* `point.rs`: example of Rust "methods" and ownership

point.rs

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#[derive(Debug)]
2+
struct Point {
3+
x: i64,
4+
y: i64,
5+
}
6+
7+
impl Point {
8+
fn new(x: i64, y: i64) -> Point {
9+
Point{ x, y }
10+
}
11+
12+
fn flip(&mut self) {
13+
let tmp = self.x;
14+
self.x = self.y;
15+
self.y = tmp;
16+
}
17+
18+
fn flipped(&self) -> Point {
19+
Point{ x: self. y, y: self. x }
20+
}
21+
22+
fn collapse(self) -> i64 {
23+
self.x + self.y
24+
}
25+
}
26+
27+
fn main() {
28+
let mut p = Point::new(3, 4);
29+
println!("{:?}", p.flipped());
30+
p.flip();
31+
println!("{:?}", p);
32+
println!("{}", p.collapse());
33+
}

0 commit comments

Comments
 (0)