Why can't function expecting immutable arg take mutable input?

Daniel Kozak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 16 03:53:13 PDT 2015


Shriramana Sharma píše v Pá 16. 10. 2015 v 16:05 +0530:
> Hello. I still haven't wrapped my mind around the const/immutable
> thing yet 
> and am still stuck in C/C++ mode. :-(
> 
> A function that takes mutable arguments cannot be called with
> immutable 
> input at the call site since it does not promise to *not* mutate the
> input. 
> That's of course clear.
> 
> Why can't a function that takes an immutable argument be called with
> a 
> mutable input at the call site?
> 
> IOW, why isn't mutable implicitly convertible to immutable?
> 
> I just finished writing a string processing module which calls
> multiple 
> subroutines, and all of them carrying arguments with type `string`
> viz. 
> `immutable(char)[]` IIUC, and I tried to pass it something which came
> from 
> File.byLine(), then got the error:
> 
> function textattr.applyTextAttr (string text) is not callable using
> argument 
> types (char[])
> 

Because immutable means it could resist in ROM so there could be some
optimalization. Const on the other hand is what you are looking for.

> I understand that const can refer to either mutable or immutable, so
> does 
> this mean I should replace all occurrences of `string` in arguments
> and 
> return values of functions by `const(char)[]`?
> 

Yes you could, but be carefull that you do not store result
from File.byLine() without dup or idup, because with next calling of
File.byLine() it will probably modificate the previous result.


More information about the Digitalmars-d-learn mailing list