Hey folks (guys and gals alike), I've got a little practical joke for you. I've totally fallen in love with the std/options library and slap it everywhere there's an optional value. I use it so much that the name "Option" started bugging me—it keeps clashing with half the other libraries out there that also decided to call something "Option." So I thought, why not borrow a bit of inspiration from Haskell? And voilà, I whipped up this tiny module:
import std/options
type
Maybe* [T] = Option[T]
export options except Option
I totally get that renaming something in the standard library isn’t going to happen—backward compatibility is sacred, and for most folks it’d just be unnecessary churn. Besides, the biggest headache I caused myself: years ago I wrote a little wrapper over std/parseopt, and—of course—in my infinite wisdom I called the type Options in there. Classic self-own. 😅 I’m definitely not alone though; the word “Option” pops up all over the place in Nim projects. Not everyone is as hopelessly addicted to std/options as I am. Anyway, one of the truly beautiful things about Nim is how effortlessly you can tweak the syntax to suit your own quirks and preferences. So consider this tiny snippet a little open-source Christmas gift—you’re welcome to use it however you like. By the way, a random thought just hit me: do you think std/options adds any noticeable overhead to a program? Is a plain old isNil check faster or somehow better? My gut says the runtime cost is negligible and the ergonomics of Option are just too nice to pass up—but I’m curious what you all think!
By the way, a random thought just hit me: do you think std/options adds any noticeable overhead to a program? Is a plain old isNil check faster or somehow better? My gut says the runtime cost is negligible and the ergonomics of Option are just too nice to pass up—but I’m curious what you all think!
Zero overhead, Option for pointer is just syntactic sugar but compiles to the same raw pointer code.
https://github.com/nim-lang/Nim/blob/v2.2.6/lib/pure/options.nim#L90-L99
type
Option*[T] = object
## An optional type that may or may not contain a value of type `T`.
## When `T` is a a pointer type (`ptr`, `pointer`, `ref`, `proc` or `iterator {.closure.}`),
## `none(T)` is represented as `nil`.
when T is SomePointer:
val: T
else:
val: T
has: bool