首页 > 解决方案 > 在 Julia 中重新分配 Union{Nothing, Float64} 类型的可变结构字段

问题描述

假设我有一个简单的可变结构,其字段可以是浮点数或空值

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

foo = Foo(0.42)
foo.bar = Nothing

如果我尝试将 Nothing 分配给它,我会收到此错误:

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

我应该以不同的方式定义我的结构吗?或者还有其他方法可以解决这个问题吗?

先感谢您

标签: structjuliaunionsnothing

解决方案


使用foo.bar = nothing. Nothing是 的类型nothing


推荐阅读