Type of string literal concatenated with non-immutable char array
Jacob Carlborg
doob at me.com
Mon Feb 1 10:27:29 UTC 2021
On Sunday, 31 January 2021 at 21:48:09 UTC, Per Nordlöw wrote:
> Given
>
> char x[];
>
> why is
>
> typeof("a" ~ x)
>
> `char[]` when
>
> typeof("a" ~ x.idup)
>
> is
>
> `string`?
>
> My case is
>
> class NameLookupException : Exception
> {
> this(string name) {
> super("Name " ~ name ~ " could not be found");
> }
> this(scope const(char)[] name) {
> super("Name " ~ name.idup ~ " could not be found");
> }
> }
>
> where I instead would like to only need
>
> class NameLookupException : Exception
> {
> this(scope const(char)[] name) {
> super("Name " ~ name ~ " could not be found");
> }
> }
>
> Why isn't
>
> "Name " ~ name ~ " could not be found"
>
> implicitly convertible to `string`?
Because if you have arrays of reference types, it's possible to
change an element of the mutable array, which will affect the
immutable array, those breaking the immutability. Example:
class Foo
{
int a;
}
void main()
{
Foo[] a = [new Foo];
immutable(Foo)[] b = [new Foo]; // `string` is an alias for
`immutable(char)[]`
auto c = b ~ a;
a[0].a = 3;
assert(c[1].a == 3);
}
Due to language consistency it should behave the same for all
types.
In the above example, `c` is typed as `const(Foo)[]`. Although, I
wonder why in your example the concatenation is typed as `char[]`
instead of `const(char)[]`. Perhaps that's a bug.
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list