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

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 16 07:43:27 PDT 2015


On Friday, October 16, 2015 12:35 PM, Shriramana Sharma wrote:

> 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?

immutable says that the data won't ever change. If references to mutable 
data would be implicitly convertible to immutable, then you could break the 
immutable guarantee by mutating through the mutable reference which would 
also be visible through the immutable reference.

Keep in mind that functions/methods may store references and reuse them on 
subsequent calls. If the parameter is immutable, then the function can 
assume that the data doesn't change in between calls. If you could pass 
mutable data, then you could change it between calls, and the function's 
immutability expectation would fail.

Also, multiple threads may work concurrently on the same data. But if you 
could have an immutable reference in one thread and a mutable one in 
another, then "immutable" data could change while the function runs.

An immutable parameter is as much a demand by the function from the caller 
as it is a guarantee to the caller. If you don't need the demand part, and 
only want to guarantee that the function does not alter the argument 
(through that reference), const does that.

> 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[])
> 
> 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)[]`?

If the functions don't actually require immutable data, then yes, use const 
instead.


More information about the Digitalmars-d-learn mailing list