I just learned from Why are ref's in structs type unstable? that Ref is not a concrete type, and so structs containing a Ref are not type-stable, e.g.
struct Foo
a::Ref
end
Instead you have to use, for example, RefValue like
struct Bar
a::RefValue
end
As a new-ish user, who was introduced to Ref as “if you have to use a mutable, global variable, make it a const Ref so that it is type stable” (I know this is out of date now, since we can now declare types for global variables), it was surprising that putting a Ref in a struct is type unstable.
The documentation for Core.Ref (C Interface · The Julia Language) does implicitly tell you this, as it has an example
julia> Ref(5)
Base.RefValue{Int64}(5)
where you can see that the concrete type is Base.RefValue rather than Ref, but there is no explicit discussion and no warning about type instability.
Question: what is best practice for using Ref, and should it be documented more clearly?
In a quick search, the Discourse topic linked above was the only discussion I found about Ref and type stability, and the only documentation for Ref seems to be the docstring - did I miss something? If not, I think more guidance for usage would be good.
For a bit more detail on why I care: I’ve fallen into a pattern where when I want a mostly immutable struct, but one or two fields need to be mutable, I’ve made those fields Ref variables, assuming that this was a safe and sensible thing to do. Is this bad practice? Should I just use a mutable struct instead? Is using Base.RefValue instead of Ref the right thing to do?
As Base.RefValue is not exported from Base, it doesn’t seem like an obvious thing to choose as a user!