Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In julia, where struct argument names are coming from?

I have a newbie question. What I understand that a struct will have fields and once pass them by order. Like :

julia> struct Foo
           bar
           baz
       end

julia> foo = Foo(1, 2)
Foo(1, 2)

In something like Makie, the main struct is Figure(). All the tutorials are showing customized arguments like backgroundcolor, resolution …etc.

f = Figure(backgroundcolor = :tomato)

But in the docstring, there is no mentioning for these keywords.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you in advance

>Solution :

I think this is a duplicate of: Pass arguments to @kwdef struct programmatically

But to answer your question, as shown there you can have keyword fields by placing the Base.@kwdef macro before struct, i.e.:

Base.@kwdef struct Foo
    bar = nothing
    baz = nothing
end

Then doing Foo(baz=3) returns Foo(nothing,3) etc.

To answer your question about what they do in Makie, here is their relevant bit of code for making Figures (from their GitHub source code):

function Figure(; kwargs...)

    kwargs_dict = Dict(kwargs)
    padding = pop!(kwargs_dict, :figure_padding, theme(:figure_padding))
    scene = Scene(; camera=campixel!, kwargs_dict...)
    padding = convert(Observable{Any}, padding)
    alignmode = lift(Outside ∘ to_rectsides, padding)

    layout = GridLayout(scene)

    on(alignmode) do al
        layout.alignmode[] = al
        GridLayoutBase.update!(layout)
    end
    notify(alignmode)

    f = Figure(
        scene,
        layout,
        [],
        Attributes(),
        Ref{Any}(nothing)
    )
    # set figure as layout parent so GridPositions can refer to the figure
    # if connected correctly
    layout.parent = f
    f
end

They create a dictionary based on the keyword arguments, then pass those manually to the Figure struct, which is defined as:

struct Figure
    scene::Scene
    layout::GridLayoutBase.GridLayout
    content::Vector
    attributes::Attributes
    current_axis::Ref{Any}

    function Figure(args...)
        f = new(args...)
        current_figure!(f)
        f
    end
end

So they use the Figure function to access the keyword arguments and then pass the appropriate keywords to the Figure struct.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading