const, enum, immutable, and bool Conversions
Learn about const, enum, immutable, and bool conversions.
We'll cover the following...
We'll cover the following...
const
conversions
As you know, reference types can automatically be converted to the const
of the same type. Conversion to const
is safe because the width of the type does not change and const
is a promise to not modify the variable:
Press + to interact
D
import std.stdio;char[] parenthesized(const char[] text) {return "{" ~ text ~ "}";}void main() {char[] greeting;greeting ~= "hello world";write(parenthesized(greeting));}
The mutable greeting
above is automatically converted to a const char[]
as it is passed to parenthesized()
.
As you have also seen earlier, the opposite conversion is not automatic. A const
reference is not automatically converted to a mutable reference:
Press + to interact
D
import std.stdio;char[] parenthesized(const char[] text) {char[] argument = text; // ← compilation ERRORreturn argument;}void main() {char[] greeting;greeting ~= "hello world";write(parenthesized(greeting));}
Note that this topic is only about references. Since variables of value types are copied, it is not possible to affect the original ...