Advertisement
Guest User

Untitled

a guest
Dec 10th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. const Shape = struct {
  2. areaFn: fn (self: *const Shape) f64,
  3.  
  4. pub fn area(self: *const Shape) f64 {
  5. return self.areaFn(self);
  6. }
  7. };
  8.  
  9. const Square = struct {
  10. shape: Shape,
  11. length: f64,
  12.  
  13. pub fn init(length: f64) Square {
  14. return Square{
  15. .shape = Shape{ .areaFn = areaFn },
  16. .length = length,
  17. };
  18. }
  19.  
  20. pub fn areaFn(shape: *const Shape) f64 {
  21. const self = @fieldParentPtr(Square, "shape", shape);
  22. return self.length * self.length;
  23. }
  24. };
  25.  
  26. test "square" {
  27. const square = Square.init(5);
  28. std.testing.expectEqual(square.shape.area(), 25);
  29. }
  30.  
  31. const Triangle = struct {
  32. shape: Shape,
  33. base: f64,
  34. height: f64,
  35.  
  36. pub fn init(base: f64, height: f64) Triangle {
  37. return Triangle{
  38. .shape = Shape{ .areaFn = areaFn },
  39. .base = base,
  40. .height = height,
  41. };
  42. }
  43.  
  44. pub fn areaFn(shape: *const Shape) f64 {
  45. const self = @fieldParentPtr(Triangle, "shape", shape);
  46. return self.base * self.height / 2;
  47. }
  48. };
  49.  
  50. test "triangle" {
  51. const triangle = Triangle.init(10, 3);
  52. std.testing.expectEqual(triangle.shape.area(), 15);
  53. }
  54.  
  55. test "heterogenous list" {
  56. var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
  57. defer arena.deinit();
  58. const allocator = &arena.allocator;
  59.  
  60. var shapes = std.ArrayList(*const Shape).init(allocator);
  61.  
  62. var triangle = try allocator.create(Triangle);
  63. triangle.* = Triangle.init(10, 15);
  64. try shapes.append(&triangle.shape);
  65.  
  66. var square = try allocator.create(Square);
  67. square.* = Square.init(10);
  68. try shapes.append(&square.shape);
  69.  
  70. std.testing.expectEqual(shapes.at(0).area(), 75);
  71. std.testing.expectEqual(shapes.at(1).area(), 100);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement