Delete Function for a struct instance

Hello internet.

I’m defining my own struct, and it does something on PC internals when it is created. I would to perform other operations (some deleting files) when the struct instance is no more in use. Here an simple example.

mutable struct aStruct
    value1
    value2
    value3
    function aStruct(value1, value2, value3) 
        call_this_function_when_Creating_struct_instance()
        new(value1,value2,value3)
    end

    function call_this_function_when_Creating_struct_instance()
        println("Doing some internal operations ...")
    end
    function call_this_function_when_Deleting_struct_instance()
        println("Deleting...")
    end
end

firstInstance = aStruct(1,1,1)

function dummy()
    secondInstance = aStruct(1,1,0) 
    secondInstance = "here the value of secondInstance is lost"
    return nothing
end

dummy()

When firstInstance is created, the message Doing some... appears on terminal as expected :+1:

But look at dummy() function. I’ve created secondInstance and I lose its data.

I would like to run call_this_function_when_Deleting_struct_instance() at the end of the dummy() function automatically. My guess is that I have to configure the Garbage Collector, but I have no idea of how to do it

Any suggestions :thinking:?

You can use the finalizer but there’s no guarantee when it’ll run. You must not depend on it to run at any given time and there’s no way to run some code immediately when an object becomes unreachable. If you want something to run at the end of a scope, you should create such functionality manually with try catch (slow) or macro (or both)

1 Like

I had a similar situation arise with a hardware interface that needed
startup and shutdown. Here you can use finalizer(), but since it may not
run until exit, you can add a reference count, more or less like:

module Foo

const _INSTANCE_COUNT = [0]

mutable struct aStruct
    value1
    value2
    value3
    function aStruct(value1, value2, value3) 
        this = new(value1,value2,value3)
        call_this_function_when_Creating_struct_instance(this)
        this
    end

    function call_this_function_when_Creating_struct_instance(this)
        if _INSTANCE_COUNT[1] == 0
            println("Doing some internal operations ...")
        end
        _INSTANCE_COUNT[1] += 1
        finalizer(call_this_function_when_Deleting_struct_instance, this)
    end
    function call_this_function_when_Deleting_struct_instance(this)
        println("Deleting...")
        if (_INSTANCE_COUNT[1] -= 1) == 0
         ...
        end
    end
end

firstInstance = aStruct(1,1,1)

function dummy()
    secondInstance = aStruct(1,1,0) 
    secondInstance = "here the value of secondInstance is lost"
    return nothing
end

dummy()


end