On Tuesday, 17 May 2022 at 00:10:55 UTC, Alain De Vos wrote:
Let's say a shape is ,a circle with a radius ,or a square with
a rectangular size.
I want to pass shapes to functions, eg to draw them on the
screen,
draw(myshape) or myshape.draw();
But how do i implement best shapes ?
You could also do something like:
```d
import std;
struct Circle {
double radius;
void draw() {
writeln(format!"Draw a circle of radius %s"(radius));
}
}
struct Rectangle {
double width;
double height;
void draw() {
writeln(format!"Draw a rectangle of width %s and height
%s."(width,height));
}
}
alias Shape = SumType!(Circle,Rectangle);
void main() {
Shape[] shapes = [Shape(Rectangle(2.0,3.)),Shape(Circle(3.0))];
foreach(shape; shapes) { shape.match!(x=>x.draw); }
}
```
or
```d
import std;
struct Circle {
double radius;
}
struct Rectangle {
double width;
double height;
}
alias Shape = SumType!(Circle,Rectangle);
struct Drawer {
int drawerState;
void drawShape(Shape shape) {
shape.match!(x=>drawShape(x));
}
void drawShape(Circle circle) {
writeln(format!"Draw a circle of radius
%s"(circle.radius));
}
void drawShape(Rectangle rectangle) {
writeln(format!"Draw a rectangle of width %s and height
%s."(rectangle.width,rectangle.height));
}
}
void main() {
Shape[] shapes = [Shape(Rectangle(2.0,3.)),Shape(Circle(3.0))];
Drawer d;
foreach(shape; shapes) { d.drawShape(shape); }
}
```