4
votes

I'm debugging some Julia code and trying to figure out why the following doesn't work. (julia 0.6.3)

struct Foo
    foo::String
end

k = Foo("bar")

finalizer(k, k->print("finalized!"))

While I expect it to print "finalized!", in actuality I get the following error:

ERROR: objects of type Foo cannot be finalized
Stacktrace:
 [1] finalizer(::Any, ::Any) at ./base.jl:127

I could find very little documentation on finalizer function, and no examples, what am I doing wrong?

1

1 Answers

5
votes

If you look up finalizer help you will learn that the type of object must be a mutable struct.

And in particular in finalizer definition in base.jl file you can see that there is a check:

if isimmutable(o)
    error("objects of type ", typeof(o), " cannot be finalized")
end

meaning that you cannot set a finalizer for immutable objects.

In Julia 0.7 the syntax of finalizer is a bit different, but the behavior is the same, see https://github.com/JuliaLang/julia/blob/master/base/gcutils.jl#L15.

Here is an example with a mutable struct:

julia> mutable struct Foo
           foo::String
       end

julia> k = Foo("bar")
Foo("bar")

julia> finalizer(k, k->print("finalized!"))

julia> finalize(k)
finalized!