Nim Generics — Type-Parameterized Procedures and Types
DodaTech
Updated 2026-06-29
1 min read
In this tutorial, you will learn about Nim Generics. We cover key concepts, practical examples, and best practices to help you master this topic.
Generics let you write code that works with multiple types while maintaining full type safety.
# Generic procedure
proc echoTwice[T](x: T) =
echo x
echo x
echoTwice(42) # T is int
echoTwice("hello") # T is string
# Generic type
type
Stack[T] = object
data: seq[T]
proc push[T](s: var Stack[T], item: T) =
s.data.add(item)
proc pop[T](s: var Stack[T]): T =
s.data.pop()
var intStack: Stack[int]
intStack.push(1)
intStack.push(2)
echo intStack.pop() # => 2
← Previous
Nim Objects — Inheritance, Methods, and Object-Oriented Programming
Next →
Nim Iterators and Sequences — Lazy and Eager Collection Processing
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro