Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const Shape = struct {
- areaFn: fn (self: *const Shape) f64,
- pub fn area(self: *const Shape) f64 {
- return self.areaFn(self);
- }
- };
- const Square = struct {
- shape: Shape,
- length: f64,
- pub fn init(length: f64) Square {
- return Square{
- .shape = Shape{ .areaFn = areaFn },
- .length = length,
- };
- }
- pub fn areaFn(shape: *const Shape) f64 {
- const self = @fieldParentPtr(Square, "shape", shape);
- return self.length * self.length;
- }
- };
- test "square" {
- const square = Square.init(5);
- std.testing.expectEqual(square.shape.area(), 25);
- }
- const Triangle = struct {
- shape: Shape,
- base: f64,
- height: f64,
- pub fn init(base: f64, height: f64) Triangle {
- return Triangle{
- .shape = Shape{ .areaFn = areaFn },
- .base = base,
- .height = height,
- };
- }
- pub fn areaFn(shape: *const Shape) f64 {
- const self = @fieldParentPtr(Triangle, "shape", shape);
- return self.base * self.height / 2;
- }
- };
- test "triangle" {
- const triangle = Triangle.init(10, 3);
- std.testing.expectEqual(triangle.shape.area(), 15);
- }
- test "heterogenous list" {
- var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
- defer arena.deinit();
- const allocator = &arena.allocator;
- var shapes = std.ArrayList(*const Shape).init(allocator);
- var triangle = try allocator.create(Triangle);
- triangle.* = Triangle.init(10, 15);
- try shapes.append(&triangle.shape);
- var square = try allocator.create(Square);
- square.* = Square.init(10);
- try shapes.append(&square.shape);
- std.testing.expectEqual(shapes.at(0).area(), 75);
- std.testing.expectEqual(shapes.at(1).area(), 100);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement