Search code examples
structjuliaunions

Re-assign mutable struct field of type Union{Nothing, Float64} in Julia


Let's say I have a simple mutable struct with a field that can be a Float or Nothing

mutable struct Foo
    bar::Union{Nothing, Float64}
end

foo = Foo(0.42)
foo.bar = Nothing

If I try to assign Nothing to it, I get this error:

MethodError: Cannot `convert` an object of type Type{Nothing} to an object of type Float64

Should I define my struct differently? Or is there another way around this?

Thank you in advance


Solution

  • Use foo.bar = nothing. Nothing is the type of nothing.