On Saturday, 14 August 2021 at 23:09:14 UTC, Paul Backus wrote:
On Saturday, 14 August 2021 at 14:04:47 UTC, kdevel wrote:
~~~
char [7] d7 = "x"; // okay
string s = "x";
char [7] c7 = s; // throws RangeError
~~~
What justifies that the compiler behaves differently on two
terms ('s', '"x"') which are of equal size, type, length and
value?
Literals in D can have different types in different contexts.
For example:
```d
byte b = 16; // 16 is treated as a byte literal
int n = 16; // 16 is treated as an int literal
b = n; // Error: cannot convert int to byte
```
The wording of the error message
~~~d
void main () // bi.d
{
byte b = 257;
}
$ dmd bi.d
bi.d(3): Error: cannot implicitly convert expression `257` of
type `int` to `byte`
~~~
does not seem to support your interpretation. The term `257` does
not encode a ‘polymorphic’ entity but the int value 257 which is
used to initialize a variable. If necessary, the value is
converted. The literal is not “typeless” as in Go [1] either.
Similarly, the string literal `"x"` can be treated either as a
`string` (a dynamic array of `immutable(char)`) or as a static
array of `char`, depending on the type of variable it's
assigned to.
[1] https://blog.golang.org/constants