Other: Struct and type alias - Polygon
-
struct
-
type
-
The simplest way to represent a polygon (a series of points) is a vector of
Pointinstances. -
We can even give it a name using the type keyword.
-
Despite its name it does not create a new type, just an alias.
-
That’s why we cannot use
implto add a method.
struct Point {
x: i32,
y: i32,
}
type Polygon = Vec<Point>;
// cannot define inherent `impl` for a type outside of the crate where the type is defined
// impl Polygon {
// fn length(&self) {
// }
// }
fn main() {
let poly: Polygon = vec![
Point { x: 3, y: 7 },
Point { x: 10, y: 6 },
Point { x: 23, y: 12 },
Point { x: -2, y: -2 },
];
for point in poly {
println!("x: {} y: {}", point.x, point.y)
}
}
x: 3 y: 7
x: 10 y: 6
x: 23 y: 12
x: -2 y: -2