Does this/self keyword exist in Nim-lang? I could not find it.
If it does not then why?
this/self keyword is often used in OOP
For example:
type
Obj[T] = object
n: T
foo: proc(): T
this: ptr Obj[T]
proc New[T](cl: proc (): T {.closure.}): Obj[T] =
result = Obj[T](n:cl())
result.this = addr result
let this = result.this
result.foo = proc(): auto = this.n
proc new (): string = "Yep"
var nn = New(new)
echo nn.n
nn.n = "No Yep"
echo nn.foo()
It is a very unsafe way of this implementation.
Are there other ways to do this?
Thanks
There are no classes in nim, therefore no 'this'. But since 'this' is usually an implicit parameter, there should be no dangers:
proc foo(this: Obj, arg1: int, arg2: bool) =
if this.field1 < arg1:
this.foo(arg1 - 1, arg2)
else:
return
Also, since methods can dispatch more than one argument, it would be hard to know which one to call 'this':
type
A = ref object of RootObj
AA = ref object of A
B = ref object of RootObj
BB = ref object of B
method test(a: A, b: B) {.base.} = echo "BASE"
method test(a: AA, b: B) = echo "AA B"
method test(a: A, b: BB) = echo "A BB"
method test(a: AA, b: BB) = echo "AA BB"
test A(), B()
test AA(), B()
test A(), BB()
test AA(), BB()
A this or self keyword or pseudo-variable doesn't make much sense in a language with multi-methods. If you want to dispatch on the primary argument of a method, you can name that parameter self or this as a matter of convention.
One thing that often throws programmers coming from traditional class-based OO languages for a loop is that in a multi-method design, type and module are not one and the same thing (as opposed to Java, C#, or Eiffel, where classes function both as types and modules encapsulating those types). If you want to emulate a traditional class, you'll do it in a multi-method design by encapsulating both the type describing the object's state, the procedures that function as constructors, and the methods that operate on the type in the same module. Importantly, the methods are not part of the type proper (which also means that you can extend types with additional methods later).