From bb93b39b58c6ce4e8a643a5dbcb6e6757117c6c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emre=20=C5=9Eafak?= <3928300+esafak@users.noreply.github.com> Date: Wed, 23 Jul 2025 17:49:31 -0400 Subject: [PATCH] docs: Add example to tutorial for interfaces using closures (#25068) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 Co-authored-by: Andreas Rumpf --- doc/tut2.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/doc/tut2.md b/doc/tut2.md index 1b59288d5b..94434a84c8 100644 --- a/doc/tut2.md +++ b/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 ------------------------