Stream: helpdesk (published)

Topic: Ref vs Union{T, Nothing}


view this post on Zulip James Wrigley (Oct 09 2025 at 08:58):

Are there any opinions on whether it's better to use a Ref or Union{T, Nothing} type as a kind of nullable type? I vaguely prefer a union as a matter of style, but maybe Ref's are better for type-stability and error messages. Though one downside of a Ref is that AFAIK there's no way to unassign one.

view this post on Zulip Mason Protter (Oct 09 2025 at 09:11):

I would use a union personally

view this post on Zulip Mason Protter (Oct 09 2025 at 09:14):

I doubt there'd be any real type stability benefits to the Ref, since with the union branch you would always do a

if !isnothing(foo.field)
    your_code
else
    some_error_branch()
end

view this post on Zulip James Wrigley (Oct 09 2025 at 09:23):

I should, but I admittedly I don't always remember to :peep:

view this post on Zulip Jakob Nybo Nissen (Oct 09 2025 at 11:28):

How can a Ref be nullable?

view this post on Zulip James Wrigley (Oct 09 2025 at 11:33):

As in you can check whether it has a value with isassigned(). And dereferencing an unassigned Ref will immediately throw an exception, which is nice.

view this post on Zulip Mason Protter (Oct 09 2025 at 11:35):

note that will only work for non-isbits types

view this post on Zulip Mason Protter (Oct 09 2025 at 11:35):

julia> r = Ref{Int}()
Base.RefValue{Int64}(140383053485888)

julia> isassigned(r)
true

view this post on Zulip James Wrigley (Oct 09 2025 at 11:36):

Ugh true, I forgot about that.

view this post on Zulip Jakob Nybo Nissen (Oct 09 2025 at 11:46):

Also you can't un-assign a Ref (if you need to)

view this post on Zulip Jakob Nybo Nissen (Oct 09 2025 at 11:46):

Just use Union :thumbs_up:

view this post on Zulip Sukera (Oct 09 2025 at 15:49):

I usually prefer Union{Some{T}, Nothing}, since that forces me to handle it and I can't forget about it anymore. The downside is that it peppers my code with @something (..) throw(...) to handle the Nothings

view this post on Zulip John Lapeyre (Oct 09 2025 at 18:16):

Sukera said:

The downside is that it peppers my code

This is the problem with the "make Julia more like Rust" program.

view this post on Zulip Sukera (Oct 09 2025 at 20:21):

Not sure what this has to do with Rust, this is just the cost of checking my callsites & the lack of syntax support for this in Julia. I personally don't mind this downside at all, because I can rest assured that I have checked every error path :shrugging:

view this post on Zulip John Lapeyre (Oct 10 2025 at 00:43):

I'm not saying that checking every error path is bad or that doing it with Union{Some{T}, Nothing} is bad. If you went through a Julia program and did this everywhere, you'd probably have a more reliable program. It would also look more like rust code than it did before you made the change.


Last updated: Oct 18 2025 at 04:39 UTC