anyway to set a const object after the fact?

Paul Backus snarwin at gmail.com
Mon Oct 29 22:12:24 UTC 2018


On Monday, 29 October 2018 at 21:50:32 UTC, aliak wrote:
> Hi, so if you have this piece of code:
>
> struct C {
>
>   void f() {
>     string[] others;
>     const string[] restArgs;
>     foreach (i, arg; args) {
>       if (isValidArg(arg)) {
>         restArgs = args[i + 1 .. $];
>         break;
>       }
>       others ~= arg;
>     }
>     // "others" is a list of args before the valid arg is 
> encountered
>     // "restArgs" is a list that is the args after the valid arg
>   }
> }
>
> Is there anyway to set a const object after declaring it in the 
> above context?
>
> Cheers,
> - Ali

Use a lambda:

const string[] restArgs = () {
   foreach(i, arg; args) {
     if (isValidArg(arg)) {
       return args[i+1 .. $];
     }
     others ~= arg;
   }
}();


More information about the Digitalmars-d-learn mailing list