我在以下 Julia 1.8 代码中收到红色警告
mutable struct S
X::Int32
const Children::Vector{Ref{S}}
end
function f2(s::Ref{S})
x = Int32(0)
chs = s[].Children
for ch in chs
add = ch[].X
x += add
end
println("f2: $(x)")
end
function test()
s = S(3, Vector{Ref{S}}())
@code_warntype f2(Ref{S}(s))
end
test()
输出:
MethodInstance for f2(::Base.RefValue{S})
from f2(s::Ref{S}) in Main at example.jl:7
Arguments
#self#::Core.Const(f2)
s::Base.RefValue{S}
Locals
@_3::Union{Nothing, Tuple{Ref{S}, Int64}} (green)
chs::Vector{Ref{S}}
x::Any (red)
ch::Ref{S} (red)
add::Any (red)
Body::Nothing
1 ─ (x = Main.Int32(0))
│ %2 = Base.getindex(s)::S
│ (chs = Base.getproperty(%2, :Children))
│ %4 = chs::Vector{Ref{S}}
│ (@_3 = Base.iterate(%4))
│ %6 = (@_3 === nothing)::Bool
│ %7 = Base.not_int(%6)::Bool
└── goto #4 if not %7
2 ┄ %9 = @_3::Tuple{Ref{S}, Int64} (red)
│ (ch = Core.getfield(%9, 1))
│ %11 = Core.getfield(%9, 2)::Int64
│ %12 = Base.getindex(ch)::Any (red)
│ (add = Base.getproperty(%12, :X))
│ (x = x + add)
│ (@_3 = Base.iterate(%4, %11))
│ %16 = (@_3 === nothing)::Bool
│ %17 = Base.not_int(%16)::Bool
└── goto #4 if not %17
3 ─ goto #2
4 ┄ %20 = Base.string("f2: ", x)::String
│ %21 = Main.println(%20)::Core.Const(nothing)
└── return %21
据我所知,ch
的类型可以在编译时确定。
不应有任何歧义。
最佳答案
Ref
是抽象的。请改用 Base.RefValue
这是它的具体子类型,因为这可能是您想要的:
julia> mutable struct S
X::Int32
const Children::Vector{Base.RefValue{S}}
end
julia> function f2(s::Ref{S})
x = Int32(0)
chs = s[].Children
for ch in chs
add = ch[].X
x += add
end
println("f2: $(x)")
end
f2 (generic function with 1 method)
julia> function test()
s = S(3, Vector{Ref{S}}())
@code_warntype f2(Ref{S}(s))
end
test (generic function with 1 method)
julia> test()
MethodInstance for f2(::Base.RefValue{S})
from f2(s::Ref{S}) @ Main REPL[11]:1
Arguments
#self#::Core.Const(f2)
s::Base.RefValue{S}
Locals
@_3::Union{Nothing, Tuple{Base.RefValue{S}, Int64}}
chs::Vector{Base.RefValue{S}}
x::Int32
ch::Base.RefValue{S}
add::Int32
Body::Nothing
1 ─ (x = Main.Int32(0))
│ %2 = Base.getindex(s)::S
│ (chs = Base.getproperty(%2, :Children))
│ %4 = chs::Vector{Base.RefValue{S}}
│ (@_3 = Base.iterate(%4))
│ %6 = (@_3 === nothing)::Bool
│ %7 = Base.not_int(%6)::Bool
└── goto #4 if not %7
2 ┄ %9 = @_3::Tuple{Base.RefValue{S}, Int64}
│ (ch = Core.getfield(%9, 1))
│ %11 = Core.getfield(%9, 2)::Int64
│ %12 = Base.getindex(ch)::S
│ (add = Base.getproperty(%12, :X))
│ (x = x + add)
│ (@_3 = Base.iterate(%4, %11))
│ %16 = (@_3 === nothing)::Bool
│ %17 = Base.not_int(%16)::Bool
└── goto #4 if not %17
3 ─ goto #2
4 ┄ %20 = Base.string("f2: ", x)::String
│ %21 = Main.println(%20)::Core.Const(nothing)
└── return %21
关于julia - 为什么这里有一个红色的警告类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76118231/