Do-Block Syntax with Where Keyword

PatrickHaecker
Mon, 03 Jun 2024 17:14:56 +0000
General Usage

I want to use a finalizer for a parametric type using the type parameter in the finalizer. I have a solution for that, but I wondered whether I can use the do syntax, but I simply do not know where the where needs to be put to be syntactically correct.
The following examples need the REPL to fire the finalizer.

Using the do syntax without a parameter works:

mutable struct MySimpleStruct
    x::String
end
s = MySimpleStruct("What is the meaning of life?");
finalizer(s) do s
    @async println("Finalizing: $(s.x)")
    return s
end;
finalize(s)

With a parametrized type, this gets a “T not defined” error, because where is missing and I do not know where to put it:

mutable struct MyStruct{T}
    x::T
end
s = MyStruct("What is the meaning of life?");
finalizer(s::T) do s
    @async println("Finalizing: $(s.x) using $(T |> nameof)")
    return s
end

Working around this is possible, but misses the typical Julia elegance:

mutable struct MyStruct{T}
    x::T
end
s = MyStruct("What is the meaning of life?");
function myfinalize(s::T) where T
    @async println("Finalizing: $(s.x) using $(T |> nameof)")
    return s
end;
finalizer(myfinalize, s);
finalize(s)

17 posts - 6 participants