-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unified syntax for function call with captured variables #10458
Comments
The current syntax calling function on a Current "method call" usage: const V = struct {
i: i32,
u: i32,
pub fn foo(this: *@This()) void {
this.i = 5;
}
};
pub fn main() !void {
var v = V{.i=42, .u=35};
const a = v.foo;
a();
} What's the type of Also, there is the issue of name shadowing: const V = struct {
i: i32,
foo: i32,
pub fn foo(this: *@This()) void {
this.i = 5;
}
};
pub fn main() !void {
var v = V{.i=42, .foo=35};
const a = V.foo; // v.foo will reference its field without compile-time warning or error
a(&v);
} This was mentioned in #6966 (comment). |
|
Lua's solution for this is simple: What I propose is related to "anonymous function" in #4170. Why don't we have syntax sugar for creating anonymous "bound" functions? Current syntax: v.foo(); Desugared current syntax: @TypeOf(v).foo(v); Proposed desugared syntax: std.xxx.partial(@TypeOf(v).foo, .{v})();
Proposed sugared syntax: (.{v} .| @TypeOf(v).foo)();
Proposed syntax (special case for "bound method" call): v.|.foo(); OK, Proposed syntax for restrictive anonymous block: .{v} .| {
// this block only have access to `v`
} Proposed syntax for arbitrary bound function: const boundf: fn () void = .{v} .| fn (v: V) void {}; |
@SpexGuy then what is the syntax for calling function in namespace of a type with a term of that type as the first variable? Still |
You can manually and explicitly construct the closure by creating a struct that contains the instance variable and function pointer. Then invoking it would just be |
That's too much text to enter on keyboard just to create a new function (if I don't need a closure) that only has access to memory where it's defined. |
Please do not file a proposal to change the language
The text was updated successfully, but these errors were encountered: