函数参数中的类型继承 [英] Type inheritance in function arguments

查看:26
本文介绍了函数参数中的类型继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在输入函数时遇到问题,我设法编写了解释问题的最少代码:

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: 没有方法匹配 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)在内存中可以有不同的表示.

The type Inner{Int64,Int64} is a concrete Inner type and it is 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.

一些例子,在用 <::

# -- 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

更新:声明不可变复合类型的方式(如原始问题中所示),已更改为:

Update: The way to declare an immutable composite type (as in the original question), have changed to:

struct Inner{B<:Real, C<:Real}
    a::B
    c::C
end

struct Outer{T}
    a::T
end

此外,可以使用参数类型声明函数 g:

Furthermore, function g could be declared with a parametric type:

function g(a::T) where T Outer{<:Inner}
    println(a)
    println(a.a)
    println(a.c)
end

因此,在调用函数之前无需创建Outer 的实例.

And hence, there is no need to create an instance of Outer before calling the function.

julia> ft64 = Inner(1.1, 2.2)
Inner{Float64,Float64}(1.1, 2.2)

julia> g(ft64)
Inner{Float64,Float64}(1.1, 2.2)
1.1
2.2

julia> i64 = Inner(3, 4)
Inner{Int64,Int64}(3, 4)

julia> g(i64)
Inner{Int64,Int64}(3, 4)
3
4

这篇关于函数参数中的类型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆