Skip to content

Feature request: @get for Short-circuiting version of get #58233

@Beforerr

Description

@Beforerr

Maybe we could have a short-circuiting version of get? If it is desirable, I would be glad to make a PR

MWE

"""
    @get(collection, key, default)

Short-circuiting version of [`get`](@ref). See also [`@something`](@ref).
"""
macro get(collection, key, default)
    val = gensym()
    quote
        $val = get($(esc(collection)), $(esc(key)), nothing)
        !isnothing($val) ? $val : $(esc(default))
    end
end

Benchmark

d = Dict(1=>"1")

f1(d) = get(()->rand(1), d, 1)
f2(d) = get(d, 1, rand(1))
f3(d) = @get(d, 1, rand(1))

julia> @b d f1, f2, f3
(4.145 ns, 16.143 ns (2 allocs: 64 bytes), 3.653 ns)

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureIndicates new feature / enhancement requestsmacros@macros

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions