`toString()` with a Delegate Parameter
Learn how to use toString() with a delegate parameter.
We'll cover the following...
toString()
Up to this point in the course, we have defined many toString()
functions to represent objects as strings. Those toString()
definitions all returned a string without taking any parameters. As noted by the comment lines below, structs and classes tke advantage of toString()
functions of their respective members by simply passing those members to format()
:
Press + to interact
import std.stdio;import std.string;struct Point {int x;int y;string toString() const {return format("(%s,%s)", x, y);}}struct Color {ubyte r;ubyte g;ubyte b;string toString() const {return format("RGB:%s,%s,%s", r, g, b);}}struct ColoredPoint {Color color;Point point;string toString() const {/* Taking advantage of Color.toString and* Point.toString: */return format("{%s;%s}", color, point);}}struct Polygon {ColoredPoint[] points;string toString() const {/* Taking advantage of ColoredPoint.toString: */return format("%s", points);}}void main() {auto polygon = Polygon([ ColoredPoint(Color(10, 10, 10), Point(1, 1)),ColoredPoint(Color(20, 20, 20), Point(2, 2)),ColoredPoint(Color(30, 30, 30), Point(3, 3)) ]);writeln(polygon);}
In order for polygon to be ...