Reading through the documentation on constructors, I came across this example.
struct OurRational{T<:Integer} <: Real
num::T
den::T
function OurRational{T}(num::T, den::T) where T<:Integer # why is this UnionAll necessary?
if num == 0 && den == 0
error("invalid rational: 0//0")
end
g = gcd(den, num)
num = div(num, g)
den = div(den, g)
new(num, den)
end
end
The documentation explains " The first line – struct OurRational{T<:Integer} <: Real
– declares that OurRational
takes one type parameter of an integer type, and is itself a real type."
Can someone break down the signature of the inner constructor in a similar manner? I’m particularly thrown off by the need for a UnionAll type here.
As I currently understand it, the where T<:Integer
means we are defining several OurRational{T}(num::T, den::T)
one for each subtype of Integer. Why is it not possible to instead do something like function OurRational{T<:Integer}(num::T, den::T)
without the UnionAll? When I do so, I get an error saying there are too few type parameters specified in new{...}
, so I edit that line to read new{T}(num, den)
, which results in a “T is not defined” error.