1st November 2019 – Language design
, Guide
, Nim
, Programming
One feature in Nim that it shares with several other languages, especially functional ones, is implicit return of values. This is one of those small features that might just seem like a way to avoid writing return
everywhere. But in fact it can be used for much more than that! So what is implicit return? In Nim we have three ways to return a value from a procedure, you have the explicit way with return
, you have the implicit return via result
and then the implicit return via the last statement in the procedure. Consider this simple code:
proc explicit(): string =
return "Typical explicit return"
proc implicitResult(): string =
result = "Implicit return through result"
proc implicitLastStatement(): string =
"Implicit return since it's last statement"
The first procedure here does the typical return
that you’re probably familiar with. The second uses the result
variable that is available in every procedure with a return value. This is used extensively throughout Nim to build return values or just assign the return before the procedure ends. The third way is maybe the most interesting of the three, and the one this article is mainly about. Because most blocks in Nim will implicitly return the result of their last statement if it matches the return type. If you change the return type of the above statement it will tell you that you need to discard
the string. In this case the string is a literal, but it could just as well be a call to another procedure that returned a string. As you might know unused return variables need to be discarded in Nim, but if it’s the last statement in a procedure it will be returned instead.