Interfaces in GDScript
In GDScript, interfaces are not explicitly defined. Instead, we use duck typing, which means that any object can be used as long as it has the required methods. Here’s how we can implement the concept of interfaces in GDScript:
In this GDScript example, we’ve implemented the concept of interfaces using duck typing. Here’s a breakdown of the code:
We define two classes,
Rect
andCircle
, each witharea()
andperim()
methods. These methods serve as our implicit “interface”.The
measure()
function takes any object as an argument. It doesn’t specify a type, allowing it to work with any object that hasarea()
andperim()
methods.In the
_ready()
function (which is called when the script is loaded), we create instances ofRect
andCircle
and pass them to themeasure()
function.GDScript’s duck typing allows us to use both
Rect
andCircle
objects with themeasure()
function, as long as they have the required methods.
To run this script in Godot:
- Create a new script and paste this code into it.
- Attach the script to a Node in your scene.
- Run the scene.
The output will be similar to:
This example demonstrates how GDScript can achieve interface-like behavior through duck typing, allowing for flexible and reusable code without explicit interface declarations.