Cannonical way to do circular dependency in Nim -
suppose have 2 modules: 1 defines object , 1 defines objectfactory. object needs have access objectfactory use of functions, , objectfactory needs access object able instantiate objects.
what cannonical way solve in nim if object implemented in module , objectfactory implemented in module?
i assuming issue here mutually recursive types, i.e. declarations of 2 or more types refer 1 another. methods or procedures refer 1 handled fine mutually recursive imports, though 1 has careful module initialization in case.
as in other languages require mutually recursive types within same module/compilation unit, there 2 principal answers.
one solution have 2 types within same module imported both module declares object type , module declares factory type (both types still need part of same type clause). e.g., create separate file, called factory_types.nim, , put both types in it:
type objectfactory = ref object lastvalue: object x: proc(): object object = ref object factory: objectfactory this module imported both module implementing object , module implementing factory.
the other solution, can keep each type in module, parametric polymorphism, type parameter used forward declaration. e.g., do:
type objectfactory[targettype] = ref object lastvalue: targettype generator: proc(): targettype and elsewhere:
type object = ref object factory: objectfactory[object]
Comments
Post a Comment