问题描述
我在函数类型方面遇到问题,我设法编写了解释该问题的最少代码:
I'm having an issue with type in functions, I've managed to write the minimal code that explains the problem:
immutable Inner{B<:Real, C<:Real}
a::B
c::C
end
immutable Outer{T}
a::T
end
function g(a::Outer{Inner})
println("Naaa")
end
inner = Inner(1, 1)
outer = Outer(inner)
g(outer)
将导致方法错误 MethodError: no method matching g(::Outer{Inner{Int64,Int64}})
因此,基本上,我不想说Inner的类型是什么,我只想让函数确保它是Outer{Inner}
而不是Outer{Float64}
之类的东西.
Will lead to the method error MethodError: no method matching g(::Outer{Inner{Int64,Int64}})
So basically, I don't want to have to say what the types of Inner are, I just want the function to make sure that it's an Outer{Inner}
and not Outer{Float64}
or something.
任何帮助将不胜感激
推荐答案
类型Inner{Int64,Int64}
是具体的Inner
类型,它不是Inner{Real, Real}
的子类型,因为Inner
的不同具体类型(Int64或Float64 )在内存中可以有不同的表示形式.
Type Inner{Int64,Int64}
is a concrete Inner
type and it's not a subtype of Inner{Real, Real}
, since different concrete types of Inner
(Int64 or Float64) can have different representations in memory.
根据文档,函数g
应该定义为:
According to the documentation, function g
should be defined as:
function g(a::Outer{<:Inner})
println("Naaa")
end
因此它可以接受类型为Inner
的所有参数.
so it can accept all arguments of type Inner
.
一些示例,在用<:
定义g
之后:
Some examples, after define g
with <:
:
# -- With Float32 --
julia> innerf32 = Inner(1.0f0, 1.0f0)
Inner{Float32,Float32}(1.0f0, 1.0f0)
julia> outerf32 = Outer(innerf32)
Outer{Inner{Float32,Float32}}(Inner{Float32,Float32}(1.0f0, 1.0f0))
julia> g(outerf32)
Naaa
# -- With Float64 --
julia> innerf64 = Inner(1.0, 1.0)
Inner{Float64,Float64}(1.0, 1.0)
julia> outerf64 = Outer(innerf64)
Outer{Inner{Float64,Float64}}(Inner{Float64,Float64}(1.0, 1.0))
julia> g(outerf64)
Naaa
# -- With Int64 --
julia> inneri64 = Inner(1, 1)
Inner{Int64,Int64}(1, 1)
julia> outeri64 = Outer(inneri64)
Outer{Inner{Int64,Int64}}(Inner{Int64,Int64}(1, 1))
julia> g(outeri64)
Naaa
文档中的更多详细信息:参数组合输入
More details at the documentation: Parametric Composite Type
这篇关于函数参数中的类型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!