Yearly "can we please have void foo() auto" post

Anonymouse zorael at gmail.com
Thu Jul 27 15:22:45 UTC 2023


I love `auto`, it makes my life easier. The compiler infers what 
it can and I primarily enjoy the bonuses of `@safe` without 
having to annotate it manually.

But it's not always applicable.

1. Some functions I would normally declare as returning `void` 
that have return statements that should implicitly discard their 
return values.

```d
string forTheSakeOfImpurity;
int alsoForTheSakeOfImpurity;

string setString()
{
     forTheSakeOfImpurity = "blah";
     return forTheSakeOfImpurity;
}

int setInt()
{
     alsoForTheSakeOfImpurity = 42;
     return alsoForTheSakeOfImpurity;
}

auto foo(bool condition)
{
     if (condition) return setString();
     else return setInt();
}

/*
onlineapp.d(20): Error: expected return type of `string`, not 
`int`:
onlineapp.d(19):        Return type of `string` inferred here.
  */
```

Can be worked around by making it `return cast(void)` everywhere, 
but I'm appealing here to not have to.

2. Some functions that I want to coerce the return value of to a 
specific type. Related to point 1.

```d
string bar() pure
{
     Appender!(char[]) sink;
     // ...
     return sink[];
}

auto baz()
{
     Appender!(char[]) sink;
     // ...
     return sink[];
}

static assert(is(ReturnType!bar == string));
static assert(!is(ReturnType!baz == string));  // :c
```

3. Any void function that I don't want the tooling to nag about.

```d
auto foo() {}

/*
asdf.d(3:1)[warn]: Auto function without return statement, prefer 
replacing auto with void
  */
```

---

Can we please have `void foo() auto`? It would behave as `auto 
foo()` does, except enforce the return type. As a bonus we'd also 
get `string bar() auto`.

Yes, I can make it `string foo()()`. I can even `return 
cast(string)sink[]`. There are technically workarounds for all of 
this; I'm just trying to make the case for repurposing the neat 
shortcut we already have in place.


More information about the Digitalmars-d mailing list