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.
- Some functions I would normally declare as returning
void
that have return statements that should implicitly discard their return values.
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.
- Some functions that I want to coerce the return value of to a specific type. Related to point 1.
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
- Any void function that I don't want the tooling to nag about.
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.