-
Notifications
You must be signed in to change notification settings - Fork 1
Description
With the current closure rules, "object-oriented" code like this can be written, although it's a bit of a hack.
func createCounter() {
let mut x = 0;
{
add: (amount) => {
x += amount;
},
get: () => x
}
}Instead of actually having x be field inside the object, it has to be a captured variable so that the lambdas can use it with reference semantics. It would be neat however to allow lambdas declared inside objects to somehow reference the object they're declared in.
self variable
The idea is to add a self symbol which acts as an immutable variable and is implicitly declared inside object expressions. When referenced, this symbol returns the object it was declared by.
This would allow turning the above code into this (although the semantics are slightly different):
func createCounter() {
{
mut x: 0,
add: (amount) => {
self.x += amount;
},
get: () => self.x
}
}Notably self would not be permitted to be referenced within the value expressions of fields, as in
{ x: self.x }Since x is not "initialized" when self.x is evaluated, this should be an error. self should only be available inside lambdas inside objects.
Naming
The symbol could be called either self, this, or something different. Both self and this are somewhat confusing though since it's not entirely evident what "self" or "this" is. Another idea would be object, although a 6-letter name is somewhat too long imo.