Does the following piece of code (which works properly)
struct MyArray{T<:Number} <: AbstractArray{T,1}
data::Array{T,1}
end
have an equivalent where
syntax?
I tried the following
struct MyArray{T} where T<:Number <: AbstractArray{T,1}
data::Array{T,1}
end
but I got
ERROR: syntax: invalid type signature
Stacktrace:
[1] macro expansion at ./REPL.jl:97 [inlined]
[2] (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at ./event.jl:73
If is true that subtyping doesn’t admit the where
syntax, what is the reason behind?
My understanding of this was that the where
syntax was created specifically for functions, in order to avoid the ambiguity between type parameter arguments in constructors and static type parameters in non-constructor function calls. Since no such ambiguity exists when declaring a struct
, my assumption has been that the where
syntax is invalid there (the issue is handled by the various constructors).
For example, in the old syntax
f{T<:Real}(phi::T) = exp(im*phi)
can either be a function which is called like f(phi)
or a constructor which is called like f{T}(phi)
. In the new syntax
f(phi::T) where T<:Real = exp(im*phi)
makes it clear that this can only be called as f(phi)
.
2 Likes