Objects
Nim Objects
Defining Objects
Nim objects define custom types with fields and methods.
Defining a Nim Object
Nim objects are custom types that allow you to encapsulate data and functions. This is similar to structures in languages like C or classes in object-oriented languages. In Nim, you define an object using the object
keyword.
Creating and Using Nim Objects
Once you have defined an object, you can create instances of it and access its fields. Here's how you can instantiate and use a Car
object:
Methods in Nim Objects
In addition to fields, Nim objects can have methods. Methods are procedures that operate on object instances. You define methods using the proc
keyword inside the object type definition.
With the method defined, you can call it on a Car
object:
Inheritance with Nim Objects
Nim supports inheritance, allowing one object type to inherit fields and methods from another. This is useful for creating a hierarchy of objects with shared functionality. In Nim, inheritance is specified using the of
keyword.
Here, Car
inherits the wheels
field from Vehicle
. You can create a Car
object and access this inherited field:
Objects
- Objects
- Object Variants
- Enums
- References
- Previous
- Metaprogramming
- Next
- Object Variants