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.
I would use a union personally
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
I should, but I admittedly I don't always remember to :peep:
How can a Ref be nullable?
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.
note that will only work for non-isbits types
julia> r = Ref{Int}()
Base.RefValue{Int64}(140383053485888)
julia> isassigned(r)
true
Ugh true, I forgot about that.
Also you can't un-assign a Ref (if you need to)
Just use Union :thumbs_up:
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 Nothing
s
Sukera said:
The downside is that it peppers my code
This is the problem with the "make Julia more like Rust" program.
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
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