mirror of
https://github.com/nim-lang/Nim.git
synced 2025-12-28 08:54:53 +00:00
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:
20
doc/tut2.md
20
doc/tut2.md
@@ -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
|
||||
------------------------
|
||||
|
||||
Reference in New Issue
Block a user