Functions
Nim proc
Defining Procedures
Nim proc defines functions with typed parameters and returns.
Introduction to Nim proc
In Nim, functions are defined using the proc
keyword. Functions allow you to encapsulate code within a defined structure, facilitating reusability and readability. A proc
in Nim can accept parameters and return values, both of which can be explicitly typed.
Defining a Basic proc
To define a basic proc
in Nim, you use the proc
keyword followed by the function name, parameters, and return type. Here's a simple example:
In this example, the greet
proc takes a string
parameter name
and returns a string
. The function concatenates "Hello, " with the provided name.
Multiple Parameters and Return Types
Nim allows you to define procs with multiple parameters and specify the return type explicitly. You can also return multiple values using tuples. Consider the following example:
Here, the addAndMultiply
proc takes two int
parameters and returns a tuple containing the sum and product of the inputs.
Optional Parameters in procs
Nim allows default values for parameters, making them optional when calling the proc. Here's how you can define a proc with optional parameters:
In this example, the power
proc calculates the power of a base number. The exponent
parameter has a default value of 2, making it optional. If only the base is provided, the proc returns the square of the base.
Named Parameters and Order Flexibility
When calling a proc, Nim allows the use of named parameters, providing flexibility in the order of arguments. Here is an example:
In the displayInfo
proc, the parameters are specified in a different order during the call, using named parameters. This can improve code readability and maintainability.
Conclusion
Nim's proc
keyword is a powerful feature for defining functions with clear parameter and return type specifications. By leveraging features like multiple parameters, optional values, and named parameters, you can write flexible and efficient Nim code. Explore these concepts further to create robust applications.
Functions
- Previous
- echo
- Next
- Anonymous Procs