Hello everyone,
I would like to know if Nim allows me to check if a procedure exists for a given type at compile time ?
.
# As a library author I define a type `Car`
type
Car = object
speed: int
proc default_drive(self: Car):
echo "vroom"
# A user of this library define a procedure `drive` on this `Car` type
proc drive(self: Car):
echo "VROOM !!"
var car = Car()
# Somewhere in my library, I want to check if the procedure `drive` exists on type `Car`
# NB: The code below is pseudo code
if prodecure_exists(Car, "drive"):
car.drive()
else:
car.default_drive()
Have a nice day :)
A basic test is generally "when compiles()".
But I think your case can not really work: The user of your lib would import your lib, and on the other hand your lib would import drive() proc from user module. So you have cyclic imports.
Maybe your lib can define and export a proc var of type drive(), which is nil by default and user can assign his own proc to it?
Wow, I didn't think about cyclic imports at first !
I ended up with the approach you mentioned: using a proc type field with a default value that can be overriden by the end user with a setter.
Finally, messing around with type introspection would have been more complicated to understand compared to this simple solution.
.
# Define in the library
type
Callback = proc (self: Car)
Car = ref object
speed: int
drive_callback*: Callback
proc new*(car_type: type[Car]) Car =
return Car (drive_callback: default_drive)
proc default_drive(self: Car):
echo "vroom"
proc set_drive_callback*(self: Car, callback: Callback) =
self.drive_callback = callback
# Define by the user
var car = Car()
car.set_drive_callback(
proc (self: Car) =
echo "VROOM !!"
)
PS: Thanks @dawkot for the hint, I might use it for another thing !