docs: Add example to tutorial for interfaces using closures (#25068)

* Add a new section to doc/tut2.md explaining interfaces.
* Provide a code example demonstrating how to simulate interfaces using
objects of closures.
* The example shows a basic IntFieldInterface with getter and setter
procedures.

This PR was inspired by the discussion in
https://forum.nim-lang.org/t/13217

---------

Co-authored-by: Emre Şafak <esafak@users.noreply.github.com>
Co-authored-by: Andreas Rumpf <araq4k@proton.me>
This commit is contained in:
Emre Şafak
2025-07-23 17:49:31 -04:00
committed by GitHub
parent cd806f9dbe
commit bb93b39b58

View File

@@ -86,6 +86,26 @@ Student(id: 123)` will truncate subclass fields.
(*is-a* relation) for simple code reuse. Since objects are value types in
Nim, composition is as efficient as inheritance.
Interfaces
----------
Concepts like abstract classes, protocols, traits, and interfaces can be
simulated as objects of closures:
```nim
type
IntFieldInterface = object
getter: proc (): int
setter: proc (x: int)
proc outer: IntFieldInterface =
var captureMe = 0
proc getter(): int = result = captureMe
proc setter(x: int) = captureMe = x
result = IntFieldInterface(getter: getter, setter: setter)
```
Mutually recursive types
------------------------