What are ref functions in D?
What is a function?
Functions are generally code blocks that carry out certain instructions in an application. This code block can be called more than once during the application's run time or execution time if its functions are reusable.
What are ref functions?
ref functions are functions that return by reference. This is similar to the arguments of the ref function. For a better understanding, let's look at an example:
import std.stdio;ref int lesser(ref int val1, ref int val2) {return val1;}void main() {int x = 1;int y = 2;lesser(x, y) += 10;writefln("x: %s, y: %s", x, y);}
Code explanation
In the example above, we add 10 to val1 returned from the function.
- Line 3: Notice the use of the
refkeyword and its use in the arguments also.
- Line 4: We return
val1to demonstrate thereffunction.
- Line 8-9: We declare our variables.
- Line 11: We call the
reffunction. Here, we use it as a variable. We add10toval1since we only returnval1from thereffunction.
- Line 12: We printed our output to the screen.