Optional type - how to correctly reset a wrapped immutable T
jmh530
john.michael.hall at gmail.com
Tue Mar 27 13:51:20 UTC 2018
On Tuesday, 27 March 2018 at 13:02:50 UTC, aliak wrote:
>
> Hmm, now that I'm explicitly trying to produce it, I feel I
> maybe using inout incorrectly?
>
> struct Optional(T) {
> T[] bag;
> this(T t) {
> bag = [t];
> }
> }
>
> struct S {
> Optional!(inout(int)) f() inout
> {
> return Optional!(inout(int))(3);
> }
> }
>
> void main()
> {
> auto a = S().f;
> }
>
> Above gives: Error: variable
> `onlineapp.Optional!(inout(int)).Optional.bag` only parameters
> or stack based variables can be inout
>
> Change inout to const e.g. and it's all good.
You may refer to the section on struct constructors. inout on a
constructor serves as both a const and an immutable constructor.
This would allow you to create mutable/const/immutable objects of
whatever struct. The payload could have some different setting.
https://dlang.org/spec/struct.html#struct-constructor
How about:
struct Optional(T) {
T[] bag;
this(T t) {
bag = [t];
}
}
Optional!T optional(T)(T x)
{
return Optional!T(x);
}
void main()
{
int x = 3;
const(int) xx = 3;
immutable(int) xxx = 3;
auto y = optional(x);
auto yy = optional(xx);
auto yyy = optional(xxx);
}
More information about the Digitalmars-d-learn
mailing list