What are inout functions in D?

What is a function?

Functions are generally code blocks that carry out certain instructions in an application. These code blocks can be called more than once during the application's run time or execution time.

What are inout functions?

The inout function is declared using the keyword inout. It is also able to take in values through parameters and return outputs. In inout functions, mutability attributes can be transferred to the return type. In these functions, we also transform the parameter data from one type to another before returning. Let's see an example:

import std.stdio;
inout(char)[] qoutedWord(inout(char)[] phrase) {
return '"' ~ phrase ~ '"';
}
void main() {
immutable(char)[] c = "test c";
c = qoutedWord(c);
writeln(typeof(qoutedWord(c)).stringof," ", c);
}

Code explanation

  • Lines 3-5: We declare and define our inout function. Notice how we use the inout keyword while declaring the function.
  • Lines 10-12: We call the created inout function and transform a variable to another type before printing to check the new type in line 12.

Free Resources