digitalmars.D.learn - delegates that return void + lambdas
- Joshua Hodkinson (17/17) Aug 21 2017 So I have run across the following issue while working with
- Steven Schveighoffer (12/36) Aug 21 2017 You can return void when your return type is void. When the return type
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
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? ThanksYou 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