How do you do "const nazi" in D?

Steven Schveighoffer schveiguy at yahoo.com
Thu Jan 4 12:26:11 UTC 2018


On 1/3/18 12:27 PM, Marc wrote:
> for a safe programming, since C/C++ times I try to make thing const as 
> possible. locals, parameters etc anything which isn't going to change.
> How do you do that in D? immutable everywhere?

For parameters, I'd recommend const, not immutable, as const allows more 
to be passed in. If you need to return something from the parameters, 
inout should be what you use.


> for example:
> 
>>     foreach(Field field; fields) {
>>         immutable string htmlOutputfile = genHTMLFilename();

immutable is OK here, as it's not a parameter. Note, you can drop the 
"string" type, as it will be inferred.

A further note here -- immutable string can convert implicitly to 
mutable string, because the data underneath is also immutable. But you 
won't be so lucky with other data types.

You may want to be cautious when declaring something const/immutable 
inside your functions, as it may not convert for calls to other 
libraries that haven't been properly "const nazi'd".

> and on:
> 
>> Field fromFile(in string filename) {
> 
> do you use in here if filename isn't going to change?

It depends completely on your internals. In this case, you are accepting 
a string by value. The string contents are referenced, but those are 
already immutable. You can't change anything the caller passed in, even 
if this was not tagged 'in'. All you can do is rebind filename locally 
to something else. If it were me, I would do this:

Field fromFile(const(char)[] filename)

Or potentially this if you never are going to change filename internally:

Field fromFile(in char[] filename)

This allows passing any flavor of char array, so it provides a wider 
amount of access.

> I'm trying to make my own const nazi guide for D, if anyone would like 
> to give your opinion on this, I would be glad.

If you send me email when you are ready, I'll review!

As Jonathan implied, const is viral. If you try using proper const code 
with libraries that don't use it, you will have lots of trouble. So it's 
not always worth it.

-Steve


More information about the Digitalmars-d-learn mailing list