www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - delegates that return void + lambdas

reply Joshua Hodkinson <joshua.hodkinson.42 gmail.com> writes:
So I have run across the following issue while working with 
delegates and lambdas,


---
struct Struct {
	int prop;
}

alias Func = void delegate(ref Struct);
Func func = (ref s) => s.prop += 1;
---

with compiler error `Error: cannot return non-void from function`

I understand that the lambda syntax in this case would be short 
for

---
Func func = (ref s) { return s.prop += 1; };
---

But does this mean you can't have lambdas that return void?

Thanks
Aug 21 2017
parent Steven Schveighoffer <schveiguy yahoo.com> writes:
On 8/21/17 8:15 AM, Joshua Hodkinson wrote:
 So I have run across the following issue while working with delegates 
 and lambdas,
 
 
 ---
 struct Struct {
      int prop;
 }
 
 alias Func = void delegate(ref Struct);
 Func func = (ref s) => s.prop += 1;
 ---
 
 with compiler error `Error: cannot return non-void from function`
 
 I understand that the lambda syntax in this case would be short for
 
 ---
 Func func = (ref s) { return s.prop += 1; };
 ---
 
 But does this mean you can't have lambdas that return void?
 
 Thanks
You can return void when your return type is void. When the return type is void, you can't return something other than void. i.e., this should work: alias Func = int delegate(ref Struct); Or this: void foo(); // with your original Func definition Func func = (ref s) => foo(); You can also do this: Func func = (ref s) { s += 1; }; -Steve
Aug 21 2017