Loading search index…
No recent searches
No results for "Query here"
D supports methods defined on struct types.
import std.stdio; struct Rect { int width, height; // This `area` method is defined for the `Rect` struct. int area() { return width * height; } // Methods can be defined for either reference or value types. // Here's an example of a value type method. int perim() { return 2*width + 2*height; } } void main() { Rect r = Rect(10, 5); // Here we call the 2 methods defined for our struct. writeln("area: ", r.area()); writeln("perim:", r.perim()); // D automatically handles conversion between values // and references for method calls. You may want to use // a reference type to avoid copying on method calls or // to allow the method to mutate the receiving struct. Rect* rp = &r; writeln("area: ", rp.area()); writeln("perim:", rp.perim()); }
To run the program:
$ dmd -run methods.d area: 50 perim: 30 area: 50 perim: 30
Next, we’ll look at D’s mechanism for grouping and naming related sets of methods: interfaces.