goodlang / good

The Good Programming Language
BSD 3-Clause "New" or "Revised" License
29 stars 3 forks source link

Constructors & Destructors #11

Closed kirillDanshin closed 7 years ago

kirillDanshin commented 7 years ago

If new(*T) func defined in struct, it will be called via new(T) func call. If destruct(*T) func defined in struct, it will be called when GC will delete the object.

To get this done, we should implement multisignatures and allow to define new and destruct funcs in struct{} definition.

If destruct(*T) defined anywhere else, it works like custom functions and should not be called via GC event.

User should be able to define destruct(*T) in struct and destruct(*T) anywhere else in package and it should work as defined above.

package main

type A struct {
    B int
    C *A

    func new(a *A) {
        a.B = 15
        a.C = &A{
            B: a.B << 2,
        }
    }

    func destruct(a *A) {
        a.C = nil
    }
}

func (a *A) plus10() int {
    a.B += 10

    return a.B
}

type B struct {
    A
    B int
    C *A
}

func main() {
    abc := new(A)  // calls *A.new() defined in struct{}
               // but not *A.new() defined anywhere else
    abc.C.plus10() // 70
}
onokonem commented 7 years ago

do we really need these ambushes in our code?

kirillDanshin commented 7 years ago

@onokonem I think we need constructors/destructors, but we should keep migration to goodlang as easy as possible. Why you think it's bad?

kirillDanshin commented 7 years ago

needs a new GC. closed until we'll done with it.

alexclear commented 7 years ago

Recalling Golang syntax is a major pain, do we have something like 'with' block? If we do we don't need explicit destructors I'd say

kirillDanshin commented 7 years ago

@alexclear nope, we don't have that one

alexclear commented 7 years ago

I always thought that the name "destructor" was misleading a bit. It's about resource management (well, resource freeing), not about destruction. We're not in malloc() land anymore.

kirillDanshin commented 7 years ago

@alexclear note that we plan to add optional manual memory management. so we're not in malloc() land anymore, but kind of.