Search⌘ K

Return Type Attributes: auto ref and inout

Explore the role of auto ref and inout return type attributes in D functions. Understand how auto ref enables returning references or copies based on context, and how inout propagates parameter mutability to return types. This lesson helps enhance function template flexibility and code efficiency in D.

We'll cover the following...

auto ref functions

auto ref helps with functions like parenthesized() below. Similar to auto, the return type of an auto ref function is deduced by the compiler. Additionally, if the returned expression can be a reference, that variable is returned by a reference as opposed to being copied.

parenthesized() can be compiled if the return type is auto ref:

D
import std.stdio;
auto ref string parenthesized(string phrase) {
string result = '(' ~ phrase ~ ')';
return result; // ← compiles
}
void main() {
writeln(parenthesized("hello"));
}

The ...