Functions are named procedures in Nim.
A function with no input parameters and no return values would look like:
proc main = # "main" procedure (no inputs, no outputs)
# Here starts the function body
echo "Hello world"
main # Here we are calling "main"; "main()" would be valid too
the function body is indented like in python
Returning values
When the proc
returns a value we need to annotate its type:
The following is equivalent:
proc getValue():int =
50 + 20 + 10 # The last statement is returned; no need for `return` keyword
echo getValue()
and the following:
Input parameters
Input parameters need to be type annotated as well.
One input parameter and no returned value would be:
Lets say we have two input parameters. We separate them using ;
:
proc showNameAndAge(name:string; age:int) =
# param1^^^^^^^^^^^ ^^^^^^^param2
echo "Name: ", name, " is ", age, " years old"
showNameAndAge("Ana", 50)
When there are several parameters of the same type, we separate them using ,
:
proc showNameMinMax(name:string; min, max:int) =
# ^^^^^^^^ two int params
echo "Name: ", name
echo min, "<=", max
showNameMinMax("Ana", 10, 20)
input and output parameters
An example mixing input and output parameters:
and another:
discard
returned values
Whenever a procedure returns a value, it needs to be used. The following produces an error:
You need to do something with the returned value:
Or you can just do nothing:
Discarding a value might be useful when you are just interested in the side effects.
result
variable
This is a special variable with the return type and whatever it holds will be returned.