Skip to content

Commit bb93b39

Browse files
esafakAraq
andauthored
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 <[email protected]> Co-authored-by: Andreas Rumpf <[email protected]>
1 parent cd806f9 commit bb93b39

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

doc/tut2.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,26 @@ Student(id: 123)` will truncate subclass fields.
8686
(*is-a* relation) for simple code reuse. Since objects are value types in
8787
Nim, composition is as efficient as inheritance.
8888

89+
Interfaces
90+
----------
91+
Concepts like abstract classes, protocols, traits, and interfaces can be
92+
simulated as objects of closures:
93+
94+
```nim
95+
96+
type
97+
IntFieldInterface = object
98+
getter: proc (): int
99+
setter: proc (x: int)
100+
101+
102+
proc outer: IntFieldInterface =
103+
var captureMe = 0
104+
proc getter(): int = result = captureMe
105+
proc setter(x: int) = captureMe = x
106+
107+
result = IntFieldInterface(getter: getter, setter: setter)
108+
```
89109

90110
Mutually recursive types
91111
------------------------

0 commit comments

Comments
 (0)