Setting struct as default parameter of a function using struct literal?

Salih Dincer salihdb at hotmail.com
Wed Sep 13 04:33:31 UTC 2023


On Monday, 11 September 2023 at 23:47:33 UTC, H. S. Teoh wrote:
> Since the type of the parameter is already known, the compiler 
> does not need me to repeat the type name. It already knows 
> enough to figure it out on its own.  "Don't Repeat Yourself" 
> (DRY).

I think there are 3 possibilities, leaving aside what Steven 
suggested.  Well, since these options will generally be static, 
why not use a template parameter?  Besides, everything can be 
expressed with a single letter. For example:

```d
// Steven suggested...
void multiParams(bool silenceErrors = false, bool otherOption = 
true)
{
   writeln;
}

// (1) It cannot be customized.
auto someFunction(Options option = Options.init) => option;//*/

/*/ (2a) It doesn't run older versions:
auto someFunction(Options option = Options(silenceErrors: false)) 
=> option;//*/

/*/ (2b) There's a possibility of confusion:
auto someFunction(Options option = Options (false, false) => 
option;//*/

struct Options
{
   bool silenceErrors = true;
   bool printDebugs = true;

   string toString() => format("silenceErrors: %s\nprintDebugs: 
%s", silenceErrors, printDebugs);
}

import std.format, std.stdio;
void main()
{
   auto foo(T, T option = T.init)() => option;

   writeln(foo!Options);
   writeln(someFunction);
}
```

SDB at 79


More information about the Digitalmars-d-learn mailing list