RfC for language feature: rvalue struct
FeepingCreature
feepingcreature at gmail.com
Sun Jan 29 20:48:11 UTC 2023
On Sunday, 29 January 2023 at 17:41:26 UTC, Salih Dincer wrote:
> On Sunday, 29 January 2023 at 03:29:45 UTC, FeepingCreature
> wrote:
>> No, I mean
>>
>> ```
>> num1 = num2;
>> onlineapp.d(22): Error: cannot modify struct instance `num1`
>> of type `Foo!int` because it contains `const` or `immutable`
>> members
>> ```
>
> Sorry for writing an answer without doing the necessary unit
> tests. I forgot to put the type in parentheses. Here is the
> corrected version:
>
> ```d
> struct S(T)
> {
> import std.conv : to;
> import std.traits : ImmutableOf;
>
> immutable(T)[] data;
>
> this(R)(R[] data)
> {
> this.data = data.to!(ImmutableOf!T[]);
> }
>
> string toString() const
> {
> import std.format : format;
> return format("%s: %s", typeid(data), data);
> }
> }
>
> unittest
> {
> S!char test1, test2;
> alias TestType = typeof(test1.data);
>
> import std.traits : isSomeString;
> assert(is(TestType == string) &&
> isSomeString!TestType);
>
> test1 = S!char("bcd");
> test1.data ~= "234";
>
> test2 = test1;
> assert(test1 == test2);
> }
>
> void main()
> {
> import std.stdio;
>
> string str = "bcd";
>
> auto str1 = S!char(str.dup);
> auto str2 = S!char("abc");
>
> str1 = str2;
>
> str1.writeln; // const(immutable(char)[]): abc
> str2.writeln; // const(immutable(char)[]): abc
> }
> ```
>
> SDB at 79
I think you're missing the concept a bit:
```
test1 = S!char("bcd");
test1.data ~= "234";
This should emphatically *not* work. You're mutating a field of
`test1`. That's what we don't want to ever happen!
Instead, you should have to write `test1 = test1(test1.data ~
"234");`
This looks extremely similar, but the key is that the assignment
has to go through the constructor. That way, `test1` can only go
from "valid value" to "valid value".
More information about the Digitalmars-d
mailing list