Methods in Pascal
Our first example demonstrates how to define methods on struct types in Pascal.
In this Pascal example, we define a TRect
record type, which is similar to a struct in other languages. We then define two functions, Area
and Perim
, which operate on TRect
values.
Pascal doesn’t have the concept of methods attached directly to types like Go does. Instead, we define regular functions that take the record as a parameter. This achieves a similar result to Go’s methods.
In the begin
block (which is similar to the main
function in Go), we create a TRect
instance, set its width and height, and then call our functions, passing the record as an argument.
To run this program, you would typically save it as methods.pas
, compile it with a Pascal compiler, and then run the resulting executable.
Pascal doesn’t have the same concept of pointer and value receivers as Go does. In Pascal, you can pass records by value or by reference (using the var
keyword in the function parameter), but the syntax for calling the function remains the same either way.
Next, we’ll look at Pascal’s mechanism for defining interfaces, which allow for polymorphic behavior across different types.